package cn.cp; import java.util.Comparator; import java.util.Iterator; import java.util.TreeSet; //TreeSet实现排序的第二种办法:让容器本身实现排序的功能 //因为TreeSet有一构造方法:TreeSet tr=new TreeSet(Comparator c); //其参数为实现了Comparator接口的类 // //总结: //在方法一中,要让对象本身具有可比性,所以implements Comparable(形容词) //在方法二中,要让容器本身实现排序的功能,即使其变成一个可排序的容器 //所以采用了TreeSet treeSet=new TreeSet(new tempComparator()); //tempComparator类实现了implements Comparator(名词) class Beauty { private int age; private String name; public Beauty(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 "Beauty [age=" + age + ", name=" + name + "]"; } } class tempComparator implements Comparator { @Override public int compare(Object arg0, Object arg1) { Beauty beauty0 = (Beauty) arg0; Beauty beauty1 = (Beauty) arg1; if (beauty0.getAge() < beauty1.getAge()) { return -1; } if (beauty0.getAge() == beauty1.getAge()) {// 年龄相同时再比较姓名 return beauty0.getName().compareTo(beauty1.getName()); } if (beauty0.getAge() > beauty1.getAge()) { return 1; } return 0; } } public class TreeSetTest2 { public static void main(String[] args) { Beauty bea1=new Beauty(25, "aim"); Beauty bea2=new Beauty(26, "dim"); Beauty bea3=new Beauty(25, "xim"); Beauty bea4=new Beauty(29, "gim"); Beauty bea5=new Beauty(21, "zim"); TreeSet treeSet=new TreeSet(new tempComparator()); treeSet.add(bea1); treeSet.add(bea2); treeSet.add(bea3); treeSet.add(bea4); treeSet.add(bea5); Iterator iterator=treeSet.iterator(); while(iterator.hasNext()){ Beauty t=(Beauty) iterator.next(); System.out.println(t.getName()+"的年纪是"+t.getAge()); } } }
时间: 2024-10-04 00:26:31