java - 没有为带有 Comparator<Map.Entry 的 TreeMap 找到合适的构造函数

标签 java generics comparator

我想创建一个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> 的比较器应该知道怎么比较Integer , 不是 Map.Entry对象。

关于java - 没有为带有 Comparator<Map.Entry 的 TreeMap 找到合适的构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33925796/

相关文章:

java - RESTEasy 中的 ExceptionMapper 问题

java - JDateChooser setDate 调用意外结束执行

java - toJson 方法导致 UI 卡住

java - 可以构造泛型类型的泛型方法

java - 对子字符串内的子字符串进行排序

java - 是否可以使用 Hibernate 或 JPA 注释来限制 @OneToMany 集合的大小?

c# - 可以在运行时查询 C# 泛型吗?

java - 在java中获取实例化类型变量

java - 比较具有涉及 boolean 值的多个属性的列表

java - "Comparison method violates its general contract!"