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


对象实现Comparable接口

复制代码
public class Field implements Comparable<Field>{  
    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

复制代码
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<Field> list = new ArrayList<Field>();  
        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());  
        }  
    }  
}  
复制代码


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM