package cn.map_son;
import java.util.Comparator;
import java.util.Set;
import java.util.TreeMap;
/*
* TreeMap练习
*
*
* 键值都是String
* 键是自定义对象,值是String
*/
public class TreeMapDemo {
public static void main(String[] args) {
// 键值都是String
method1();
// 键是自定义对象,值是String
method2();
}
private static void method2() {
TreeMap<Teacher,String> tm = new TreeMap<Teacher,String>(new Comparator<Teacher>() {
@Override
public int compare(Teacher t1, Teacher t2) {
int sum= t1.getName().compareTo(t2.getName());
int sum1 = sum==0?t1.getAge()-t2.getAge():sum;
return sum1;
}
});
Teacher t1 = new Teacher("张财",22);
Teacher t2 = new Teacher("张圣",24);
Teacher t3 = new Teacher("魏冰",24);
Teacher t4 = new Teacher("张生",48);
Teacher t5 = new Teacher("刘",46);
tm.put(t1, "005");
tm.put(t2, "004");
tm.put(t3, "003");
tm.put(t4, "002");
tm.put(t5, "001");
Set<Teacher> set= tm.keySet();
for(Teacher key:set){
String value = tm.get(key);
System.out.println(key.getName()+"-"+key.getAge()+"--"+value);
}
}
// 键值都是String
private static void method1() {
TreeMap<String, String> tm = new TreeMap<String, String>();
tm.put("张财", "22");
tm.put("张圣", "24");
tm.put("张生", "48");
tm.put("刘", "46");
tm.put("魏冰", "24");
Set<String> set = tm.keySet();
for (String key : set) {
String value = tm.get(key);
System.out.println(key+"--"+value);
}
}
}
输出结果:
刘--46
张圣--24
张生--48
张财--22
魏冰--24
--------------
刘-46--001
张圣-24--004
张生-48--002
张财-22--005
魏冰-24--003
请问结果不是魏冰在张的前面么。为什么我这边输出不是。 |
|