package cn.cp; import java.util.Iterator; import java.util.TreeSet; //存入TreeSet集合中的元素是无序的,但有方法给它排序 //排序方式一:让元素自身具备比较性,需元素实现Comparable接口 //核心:重写Comparable接口的方法compareTo(Object obj) //if (tea.age == this.age) //年纪相同时再按照姓名排序!!! // return this.name.compareTo(tea.name); //因为String也类实现了此接口,当然就可以调用compareTo()方法 class Teacher implements Comparable { private int age; private String name; public Teacher(int age, String name) { this.age = age; this.name = name; } public int getAge() { return age; } public String getName() { return name; } @Override public String toString() { return "Teacher [age=" + age + ", name=" + name + "]"; } @Override public int compareTo(Object obj) {//按照年纪排序 Teacher tea = (Teacher) obj; if (tea.age < this.age) { return -1; } if (tea.age == this.age) {//年纪相同时再按照姓名排序!!!核心 return this.name.compareTo(tea.name); } if (tea.age > this.age) { return 1; } return 0; } } public class TreeSetTest1 { public static void main(String[] args) { Teacher teac1=new Teacher(25, "lim"); Teacher teac2=new Teacher(26, "uim"); Teacher teac3=new Teacher(55, "zim"); Teacher teac4=new Teacher(55, "mim"); Teacher teac5=new Teacher(55, "cim"); TreeSet treeSet=new TreeSet(); treeSet.add(teac1); treeSet.add(teac2); treeSet.add(teac3); treeSet.add(teac4); treeSet.add(teac5); Iterator iterator=treeSet.iterator(); while(iterator.hasNext()){ Teacher t=(Teacher) iterator.next(); System.out.println(t.getName()+"的年纪是"+t.getAge()); } } }
时间: 2024-09-21 01:52:48