- public static void main(String[] args) {
- // 用TreeSet集合储存自定义对象,实现按照年龄从小到大排序,使用TreeSet的带参构造(比较器接口的方式实现)\
- TreeSet<Person>ts = new TreeSet<>(new Comparator<Person>() {
- @Override
- public int compare(Person p1, Person p2) {
- int num = p1.getAge()-p2.getAge();
- return num == 0? p1.getName().compareTo(p2.getName()) : num;
- }
- });
- Person p1 = new Person ("周立波",20);
- Person p2 = new Person ("李咏",23);
- Person p3 = new Person ("包租公",30);
- Person p4 = new Person ("包租婆",50);
- ts.add(p1);
- ts.add(p2);
- ts.add(p3);
- ts.add(p4);
- for (Person p : ts) {
- System.out.println(p.getName() + "..." + p.getAge());
- }
- }
复制代码 |
|