【问题标题】:I can't insert data into list in java我无法将数据插入到java中的列表中
【发布时间】:2017-06-21 12:31:18
【问题描述】:

这是我的代码。我正在将地图插入列表中。但是当我直接将地图添加到表格中时。它显示错误。

import java.util.*;
class mapIn{
   public static void main(String... a){
List<Map<Integer, String>> mapList = new ArrayList<Map<Integer,String>>();
mapList.add(new HashMap<Integer,String>().put(1,"Ram"));
mapList.add(new HashMap<Integer,String>().put(2,"Shyam"));
mapList.add(new HashMap<Integer,String>().put(3,"Shyam"));
for(Map m:mapList){
        // for(Map.Entry e:m.entrySet()){
        //  System.out.println(e.getKey()+" "+e.getValue());
        // }
       Set set=m.entrySet();//Converting to Set so that we can traverse  
    Iterator itr=set.iterator();  
            while(itr.hasNext()){  
        //Converting to Map.Entry so that we can get key and value separately  
        Map.Entry entry=(Map.Entry)itr.next();  
        System.out.println(entry.getKey()+" "+entry.getValue());  
    } 
    }
}
}

【问题讨论】:

  • 错误是什么?你能格式化你的代码吗?请阅读我们的How to Ask 页面以获取有关如何改进此问题的提示
  • 返回:与 key 关联的前一个值,如果没有 key 映射,则返回 null。 (如果实现支持 null 值,则 null 返回还可以指示映射先前将 null 与 key 关联。)这是 put 返回值描述。这根本不应该编译。

标签: java list dictionary arraylist hashmap


【解决方案1】:

aibreania 的答案是更好的方法,但如果您想将其保留在一行中,您可以使用:

mapList.add(new HashMap<Integer,String>(){{ put(1,"Ram"); }});
mapList.add(new HashMap<Integer,String>(){{ put(2,"Shyam"); }});
mapList.add(new HashMap<Integer,String>(){{ put(3,"Shyam"); }});

【讨论】:

  • 我看不出它为什么不这样做的原因,它显然需要它周围的其他代码,因为 OP 有
  • 你每天都会学到新东西。我永远不会遇到这种将元素放入 HashMap 的语法
  • 它很紧凑,但确实有问题:正如讨论的here
【解决方案2】:

请分别执行初始化hashMap和将(key, value)放入映射的步骤。我重写了你的代码的第一部分:

List<Map<Integer, String>> mapList = new ArrayList<>();
for(int i = 0; i < 3; i++) mapList.add(new HashMap<Integer, String>());
mapList.get(0).put(1, "Ram");
mapList.get(1).put(2, "Shyam");
mapList.get(2).put(3, "Shyam");

我不知道您的代码是做什么用的,但是使用 ArrayList 来存储 3 个不同的 hashMap 并不是很有效。如果您可以提供更多信息,我们可以进一步改进代码。 希望能帮助到你。 :D

【讨论】:

  • 这与 OP 的问题所做的不同。
  • 这只是一个缩影。实际上,我是本科生,我正在使用它来实现加权图,我可以将权重和节点插入地图并将其存储在列表中。
【解决方案3】:

HashMap 中的 put 方法返回 String 而不是列表中基础对象的类型 (Map&lt;Integer, String&gt;)。这就是您收到该错误的原因。

你也可以这样做:

mapList.add(Collections.singletonMap(1, "Ram"));
mapList.add(Collections.singletonMap(2, "Shyam"));
mapList.add(Collections.singletonMap(3, "Shyam"));

【讨论】:

    猜你喜欢
    • 2017-01-24
    • 1970-01-01
    • 2011-08-05
    • 2017-11-08
    • 1970-01-01
    • 2019-01-07
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多