java对象排序(Comparable)详细实例

对象实现Comparable接口

package collections.sort.comparable;

public class Field implements Comparable{
	private String name;
    private int age;

    public Field() {
    }
    public Field(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
	@Override
	public int compareTo(Field o) {
		// TODO Auto-generated method stub
		 // 先按age排序
        if (this.age > o.getAge()) {
            return (this.age - o.getAge());
        }
        if (this.age < o.getAge()) {
            return (this.age - o.getAge());
        }
        
        // 按name排序
        if (this.name.compareTo(o.getName()) > 0) {
            return 1;
        }
        if (this.name.compareTo(o.getName()) < 0) {
            return -1;
        }
        
        return 0;
	}

}

测试test

package collections.sort.comparable;

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

public class Test {
	public static void main(String[] args) {
		Field f1 = new Field("tony", 19);
        Field f2 = new Field("jack", 16);
        Field f3 = new Field("tom", 80);
        Field f4 = new Field("jbson", 44);
        Field f5 = new Field("jason", 44);

        List list = new ArrayList();
        list.add(f1);
        list.add(f3);
        list.add(f4);
        list.add(f2);
        list.add(f5);
        Collections.sort(list);

        for (Field o : list) {
            System.out.println(o.getAge() + "-->" + o.getName());
        }
	}
}


你可能感兴趣的:(java)