按照名字进行比较,如果名字相同,在compareTo中比较返回值为0(TreeSet中判断是否相同的标准不再是equals,而是compareTo)
//姓名从小到大排列,姓名相同的年龄从小到大排列 @Override public int compareTo(Object o) { if(o instanceof Students){ Students s = (Students)o; // return this.name.compareTo(s.name); int compare = this.name.compareTo(s.name); //姓名不一样 if(compare != 0){ return compare; }else { //姓名一样 return Integer.compare(this.age,s.age); } }else{ throw new RuntimeException("传入数据类型不一致"); } @Test public void test13(){ TreeSet set = new TreeSet(); set.add(new Students("Tom",18,90)); set.add(new Students("Ann",19,75)); set.add(new Students("Lisa",20,86)); set.add(new Students("Jack",21,50)); set.add(new Students("Jerry",19,60)); set.add(new Students("Jerry",22,70)); Iterator iterator = set.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } }运行结果
定制排序(实现Comparator接口)在定制排序中,比较两个对象是否相同的标准为compare(),是否返回0,不再是equals()方法
TreeSet set = new TreeSet();
构造器没有参数的时候直接为自然排序
TreeSet set = new TreeSet(com);
构造器有蚕食的时候,按照com的定制排序进行排序
代码实现普通情况,按照年龄进行排序
//年龄从小到大进行排序 public void test14(){ Comparator com = new Comparator() { //按照年龄从小到大排列 @Override public int compare(Object o1, Object o2) { if(o1 instanceof Students || o2 instanceof Students){ Students s1 = (Students)o1; Students s2 = (Students)o2; return Integer.compare(s1.getAge(),s2.getAge()); }else{ throw new RuntimeException("传入数据类型不一致"); } } }; TreeSet set = new TreeSet(com); set.add(new Students("Tom",18,90)); set.add(new Students("Ann",19,75)); set.add(new Students("Lisa",20,86)); set.add(new Students("Jack",21,50)); set.add(new Students("Jerry",19,60)); set.add(new Students("Jerry",22,70)); Iterator iterator = set.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } }运行结果
排序的信息有相同的情况(年龄相同,其他信息不相同)
public void test14(){ Comparator com = new Comparator() { //按照年龄从小到大排列 @Override public int compare(Object o1, Object o2) { if(o1 instanceof Students || o2 instanceof Students){ Students s1 = (Students)o1; Students s2 = (Students)o2; // return Integer.compare(s1.getAge(),s2.getAge()); int compare = Integer.compare(s1.getAge(), s2.getAge()); if(compare != 0){ return Integer.compare(s1.getAge(),s2.getAge()); }else{ return s1.getName().compareTo(s2.getName()); } }else{ throw new RuntimeException("传入数据类型不一致"); } } }; TreeSet set = new TreeSet(com); set.add(new Students("Tom",18,90)); set.add(new Students("Ann",19,75)); set.add(new Students("Lisa",20,86)); set.add(new Students("Jack",21,50)); set.add(new Students("Jerry",19,60)); set.add(new Students("Jerry",22,70)); Iterator iterator = set.iterator(); while (iterator.hasNext()){ System.out.println(iterator.next()); } }运行截图