package cn.itcast;
import java.util.Comparator;
import java.util.TreeSet;
/*
*
*/
public class Demo9 {
public static void main(String[] args) {
//如果想在创建TreeSet集合对象时,直接让集合可以比较Person3
TreeSet set = new TreeSet(new Comparator() {
@Override
public int compare(Object o1, Object o2) {
Person3 p = (Person3)o1;
Person3 p2 = (Person3)o2;
// System.out.println("p:"+p+" p2:"+p2);
int result = 0;
result = p.getName().compareTo(p2.getName());
if(result==0) {
result = p.getAge()-p2.getAge();
}
return result;
}
});
set.add(new Person3("1韩红",43));
set.add(new Person3("2孙楠",42));
set.add(new Person3("1李健",38));
set.add(new Person3("3谭维维",41));
System.out.println(set);
}
}
|
|