package st; public class PersonBean implements Comparable<Object>{ private String name; private int age; PersonBean(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public int compareTo(Object obj) { if (!(obj instanceof PersonBean)) throw new RuntimeException(); /** * 在这里定义比较对象大小的方法 * 先进行年龄的比较,年龄不相等再进行姓名的比较 * 如果年龄与姓名都相等,那么就代表同一个对象 */ PersonBean pe = (PersonBean) obj; if (this.age > pe.age) return 1; if (this.age == pe.age) { return this.name.compareTo(pe.name); } return -1; } }
import java.util.Iterator; import java.util.TreeSet; public class Dup { public static void main(String[] args) { // 向这个集合中存储自定义对象 TreeSet<PersonBean> ts = new TreeSet<PersonBean>(); ts.add(new PersonBean("lishi", 22)); ts.add(new PersonBean("lishi1", 23)); ts.add(new PersonBean("lishi56", 25)); ts.add(new PersonBean("lishi4", 25)); //获取迭代器,取出其中的元素 Iterator<PersonBean> it = ts.iterator(); while (it.hasNext()) { PersonBean pe = (PersonBean) it.next(); System.out.println(pe.getAge() + " " + pe.getName()); } } }