TreeMap(Comparator<? super K> comparator) 构造一个新的、空的树映射,该映射根据给定比较器进行排序。
TreeMap<Student,String> tm = new TreeMap<Student,String>(new StuNameComparator());你自己构造的构造器要比较的值必须是Student的父类或者是其本身才行,而定义的比较器中要比较的是String数值和Student对象没有什么关系。
我改写了一下代码:- class StuNameComparator implements Comparator<String>//我想要按照地名排序
- {
- public int compare(String s1,String s2)
- {
- return s1.compareTo(s2);
- }
- }
- class Student{
- public String name;
- public int age;
- public Student(String name,int age)
- {
- this.name=name;
- this.age=age;
- }
-
- }
- public class Test1
- {
- public static void main(String[] args)
- {
- TreeMap<String,Student> tm = new TreeMap<String,Student>(new StuNameComparator());//传比较器的时候出错,说没有此构造方法,这是为什么呢?
- //当自定义的比较好器泛型定义为Student就不报错。
- tm.put("nanjing",new Student("blisi3",23));
- tm.put("beijing",new Student("lisi1",21));
- tm.put("wuhan",new Student("alisi4",24));
- tm.put("tianjin",new Student("lisi1",21));
- tm.put("shanghai",new Student("lisi2",22));
-
- Set<Map.Entry<String,Student>> entrySet = tm.entrySet();
- Iterator<Map.Entry<String,Student>> it = entrySet.iterator();
- while(it.hasNext())
- {
- Map.Entry<String,Student> me = it.next();
- String addr = me.getKey();
- Student stu = me.getValue();
- System.out.println(stu+":::"+addr);
- }
- }
- }
复制代码 显示的结果是:
day3anto.Student@1fb8ee3:::beijing
day3anto.Student@61de33:::nanjing
day3anto.Student@14318bb:::shanghai
day3anto.Student@ca0b6:::tianjin
day3anto.Student@10b30a7:::wuhan
这个结果显示地址是按照首字母的字母排序来排的
希望对楼主有帮助 |