首页 > 代码库 > TreeSet的定制排序
TreeSet的定制排序
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的定制排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。