1. 程式人生 > >java的Comparable介面實現自定義排序

java的Comparable介面實現自定義排序

除了利用資料庫的sql語句排序還可以利用java的Comparable介面自定義排序。

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class Employee implements Comparable<Employee> {

	private int id;
	private String name;
	private int age;
	
	public Employee(int id,String name,int age){
		this.id = id;
		this.name = name;
		this.age = age;
	}
	
	@Override
	public int compareTo(Employee o) {
		// TODO Auto-generated method stub
		if(id>o.id){
			return 1;
		}else if(id<o.id){
			return  -1;
		}
		return 0;
	}
	
	@Override
	public String toString() {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		sb.append("員工的編號"+id);
		sb.append("員工的姓名"+name);
		sb.append("員工的年齡"+age);
		return sb.toString();
	}
	
	public static void main(String[] args) {
		List<Employee> list = new ArrayList<Employee>();
		list.add(new Employee(3,"java",21));
		list.add(new Employee(31,"java1",22));
		list.add(new Employee(32,"java2",24));
		list.add(new Employee(28,"java6",25));
		
		for(Employee hh:list){
			System.out.println(hh);
		}
		
		Collections.sort(list);
		for(Employee zz:list){
			System.out.println(zz);
		}
		System.out.println();
	}

}