码迷,mamicode.com
首页 > 编程语言 > 详细

TreeSet的定制排序

时间:2014-12-07 16:26:30      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:style   blog   ar   color   sp   div   log   ad   ef   

1 compare()与hashcode()与equals()三者保持一致

@Test //定制排序
   public void testTreeSet2(){
    //1.创建一个实现Comparator接口的匿名类对象
    Comparator com = new Comparator(){
        //向TreeSet中添加Student类的对象,在此compare方法中,指明是按照Customer的哪个属性排序的
        public int compare(Object o1,Object o2){
            if(o1 instanceof Student && o2 instanceof Student ){
                Student s1 = (Student)o1;
                Student s2 = (Student)o2;
                int i = s1.getId()-s2.getId();
                if(i==0){
                    return s1.getName().compareTo(s2.getName());
                }
                else{
                    return i;
                }
            }
            return 0;
        }
    };
    //2.将此对象作为形参传递给TreeSet的构造器中
    TreeSet set = new TreeSet(com);
    //3.向TreeSet中添加compare方法中所涉及的类对象
    set.add(new Student(001,"shang"));
    set.add(new Student(005,"sfdg"));
    set.add(new Student(006,"shdsf"));
    set.add(new Student(031,"xvz"));
    set.add(new Student(031,"adf"));
    //set.add(new Student(031,"adf"));
    System.out.println(set.size());
    System.out.println(set);
}

结果:

5
[Student [id=1, name=shang], Student [id=5, name=sfdg], Student [id=6, name=shdsf], Student [id=25, name=adf], Student [id=25, name=xvz]]

TreeSet的定制排序

标签:style   blog   ar   color   sp   div   log   ad   ef   

原文地址:http://www.cnblogs.com/yjtm53/p/4149511.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!