繁体   English   中英

找不到适合Comparator的TreeMap构造函数

[英]No suitable constructor found for TreeMap with Comparator<Map.Entry

我想用一个匿名类比较器创建一个TreeMap来比较这些值。 但是,我得到一个错误。 我要去哪里错了?

private List<Map<Integer,Integer>> edges;
/*
*   init edges database
*/
private void initEdges() {
    edges = new ArrayList<Map<Integer,Integer>>();
    for(int i = 0; i < this.amountOfVertices; i++) {
        edges.add(
                new TreeMap<Integer, Integer>(
                        new Comparator<Map.Entry<Integer, Integer>>() {
                            @Override
                            public int compare(Map.Entry<Integer, Integer> i1, Map.Entry<Integer, Integer> i2)
                            {
                                int res = i1.getValue().compareTo(i2.getValue());
                                return res != 0 ? res : 1;
                            }
                        }
                )
        );
    }
}

确切的错误是

Error:(21, 21) java: no suitable constructor found for TreeMap(<anonymous java.util.Comparator<java.util.Map.Entry<java.lang.Integer,java.lang.Integer>>>)
    constructor java.util.TreeMap.TreeMap(java.util.Comparator<? super java.lang.Integer>) is not applicable
      (argument mismatch; <anonymous java.util.Comparator<java.util.Map.Entry<java.lang.Integer,java.lang.Integer>>> cannot be converted to java.util.Comparator<? super java.lang.Integer>)
    constructor java.util.TreeMap.TreeMap(java.util.Map<? extends java.lang.Integer,? extends java.lang.Integer>) is not applicable
      (argument mismatch; <anonymous java.util.Comparator<java.util.Map.Entry<java.lang.Integer,java.lang.Integer>>> cannot be converted to java.util.Map<? extends java.lang.Integer,? extends java.lang.Integer>)
    constructor java.util.TreeMap.TreeMap(java.util.SortedMap<java.lang.Integer,? extends java.lang.Integer>) is not applicable
      (argument mismatch; <anonymous java.util.Comparator<java.util.Map.Entry<java.lang.Integer,java.lang.Integer>>> cannot be converted to java.util.SortedMap<java.lang.Integer,? extends java.lang.Integer>)

我认为您提供给TreeMap<Integer,Integer>的Comparator应该知道如何比较Integer而不是Map.Entry对象。

TreeMap由其键(而不是其条目)排序。 您需要类似的东西,

edges.add(new TreeMap<Integer, Integer>(new Comparator<Integer>() {
    @Override
    public int compare(Integer o1, Integer o2) {
        return o1.compareTo(o2);
    }
}));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM