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]]