编写错误自定义Java中的TreeMap排序

时间:2016-09-25 14:12:14

标签: java collections

下面是我的类Emp和Class Mycomparator,它实现了Comparator。 两者都在同一个包装中。我收到错误,因为构造函数TreeMap(Mycomparator)未定义。我是Java新手。请帮忙。

public class Emp {

    String name;
    int eid;

    public Emp(String name, int eid){
        this.name=name;
        this.eid = eid;
    }

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Emp e1 = new Emp("shankar",333);
        Emp e2 = new Emp("Ronaldo",222);
        Emp e3 = new Emp("Messi",111);
        TreeMap<Integer,Emp> e = new TreeMap<Integer,Emp>(new Mycomparator());
        e.put(1, e1);
        e.put(2, e2);
        e.put(3, e3);

        Set<Integer> ss = e.keySet();
        for(Integer i:ss) {
            Emp ee = (Emp) e.get(i);
            System.out.println(i+"--------"+ee.eid+"======="+ee.name);
        }
    }
}

下面是我的类名Mycomparator,它实现了Comparator Interface。

public class Mycomparator  implements Comparator<Entry<Integer,Emp>> {

    @Override
    public int compare(Entry<Integer,Emp> arg0, Entry<Integer,Emp> arg1) {
        Map.Entry<Integer,Emp> obj1 = arg0;
        Map.Entry<Integer,Emp> obj2 = arg1;
        Emp e1 = (Emp) obj1.getValue();
        Emp e2 =(Emp) obj2.getValue();
        return  e1.name.compareTo(e2.name); 
        }
    }
}

1 个答案:

答案 0 :(得分:3)

排序的Map排序,而不是值,唯一可用的选项是按键(Integer)排序,而不是“条目”排序。如果要按值排序,则需要编写自己的地图。我不知道任何按值排序的库实现。