首页 > 编程 > Java > 正文

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

2019-11-10 16:52:50
字体:
来源:转载
供稿:网友

对象实现Comparable接口

package collections.sort.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

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<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());        }	}}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表