本帖最后由 陈延真 于 2013-5-30 21:27 编辑
要求:同姓名同年龄即为同一个人。
请按照姓名的长度从短到长,如果长度一样,请按年龄从大到小排序。
class TreeMapDemo {
public static void main(String[] args) {
// 创建集合对象
TreeMap<Student, String> hm = new TreeMap<Student, String>(new Comparator<Student>() {
@Override
public int compare(Student s1, Student s2) {
if(s1.getName().equals(s2.getName())){
return 0;
}else{
int num = s1.getName().length()-s2.getName().length();
int num2 = (num == 0) ? s2.getAge()-s1.getAge(): num;
}
return num2;
}
});
// 创建元素对象
Student s1 = new Student("lingqingxia", 25);
Student s2 = new Student("linzhiling", 35);
Student s3 = new Student("linxinru", 45);
Student s4 = new Student("lingqingxia", 25);
Student s5 = new Student("linzixiang", 55);
Student s6 = new Student("linzixianx", 55);
// 添加元素
hm.put(s1, "北京");
hm.put(s2, "上海");
hm.put(s3, "天津");
hm.put(s4, "湖北");
hm.put(s5, "重庆");
// 遍历
Set<Student> set = hm.keySet();
for (Student key : set) {
String value = hm.get(key);
System.out.println(key.getName() + "***" + key.getAge() + "***"
+ value);
}
}
}
|