【问题标题】:Map.Entry is a raw type. References to generic type Map<K,V>.Entry<K,V> should be [duplicate]Map.Entry 是原始类型。对泛型类型 Map<K,V>.Entry<K,V> 的引用应该是 [重复]
【发布时间】:2015-05-24 07:25:19
【问题描述】:

我在地图中使用 arrayList 分配双键并尝试从地图中检索数据,但我在下面收到此错误。我怎样才能让它工作?

此行有多个标记 - Map.Entry 是原始类型。对泛型类型 Map.Entry 的引用应该是 参数化 - 类型不匹配:无法从 Object 转换为 Map.Entry

Map<Double, ArrayList<Integer>> map = new HashMap<Double, ArrayList<Integer>>();
    else {

                Map<Double, ArrayList<Integer>> mapResult = db.detectRoute(latD, longD);
                Iterator it = mapResult.entrySet().iterator();
                while(it.hasNext()){
                    //The error starts here.
                    Entry e =  it.next();
                    double distance = entry.getkey();
                    ArrayList<Integer> value = entry.getValue();

                }

【问题讨论】:

    标签: java


    【解决方案1】:

    好吧,停止使用原始类型:

    Map<Double, ArrayList<Integer>> mapResult = db.detectRoute(latD, longD);
    Iterator<Map.Entry<Double, ArrayList<Integer>>> it = mapResult.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry<Double, ArrayList<Integer>>> e =  it.next();
        Double distance = entry.getKey();
        ArrayList<Integer> value = entry.getValue();
    }
    

    或者更简单:使用 foreach 循环:

    Map<Double, ArrayList<Integer>> mapResult = db.detectRoute(latD, longD);
    for (Map.Entry<Double, ArrayList<Integer>>> entry : mapResult.entrySet()) {
        Double distance = entry.getKey();
        ArrayList<Integer> value = entry.getValue();
    }
    

    使用 Java 8 甚至更简单:

    Map<Double, ArrayList<Integer>> mapResult = db.detectRoute(latD, longD);
    mapResult.forEach((distance, value) -> {
        // ...
    });
    

    另请阅读What is a raw type and why shouldn't we use it?

    【讨论】:

    • 谢谢,但有错字getkey()-->getKey();
    猜你喜欢
    • 2021-09-03
    • 2019-10-10
    • 1970-01-01
    • 2018-10-07
    • 2021-12-03
    • 2021-10-24
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    相关资源
    最近更新 更多