简体   繁体   English

列表<hashmap> list = new ArrayList<>(); java</hashmap>

[英]List<HashMap> list = new ArrayList<>(); In java

In java, Is this wrong?在 java 中,这是错误的吗? Whenever I tried to add something my old value is replaced with new value.每当我尝试添加一些东西时,我的旧值就会被新值替换。 Is it not possible to store data in list of hashmap like below statement?是否无法像下面的语句那样将数据存储在 hashmap 的列表中? When I store data as string List list = new ArrayList<>();当我将数据存储为字符串时 List list = new ArrayList<>(); like this.. it is working properly but when I tried to write hashmap in generic it is not returning old data.. I need your advice.像这样..它工作正常但是当我尝试用通用语言编写 hashmap 时它没有返回旧数据..我需要你的建议。

List<HashMap> dataArrayList = new ArrayList<>();
LinkedHashMap<String, String> hashMap = new LinkedHashMap<>();
for (int j = 0; j < name.length; j++) {
    System.out.print("Enter " + name[j] + ":");
    storedata[j] = scanner.next();
    hashMap.put(name[j], storedata[j]);
}

dataArrayList.add(hashMap);

Based on the code snippet provided the values in hashMap will only get updated in case there are duplicates in your name array.根据提供的代码片段,hashMap 中的值只会在您的名称数组中存在重复项的情况下才会更新。 I am not getting why you are creating a List of hashmap as you are only adding one hashmap in the list.我不明白你为什么要创建一个 hashmap 的列表,因为你只在列表中添加一个 hashmap。

I think what you are trying to say is as below name array ={tom, jerry, tom, jerry, duck} storedata array ={d1, d2, d3, d4, d5}我想你想说的是如下 name array ={tom, jerry, tom, jerry, duck} storedata array ={d1, d2, d3, d4, d5}

output: {[tom,{d1,d3}],[jerry,{d2,d4}],[duck,{d5}]} output:{[汤姆,{d1,d3}],[杰瑞,{d2,d4}],[鸭子,{d5}]}

So if you want something like this then create a HashMap as below所以如果你想要这样的东西然后创建一个 HashMap 如下


LinkedHashMap<String,List<String>> hashMap=new LinkedHashMap<>();
for (int j = 0; j < name.length; j++) {
    System.out.print("Enter " + name[j] + ":");
    storedata[j] = scanner.next();
    if(!hashMap.containsKey(name[j])
       hashMap.put(name[j],new ArrayList<>());
    hashMap.put(name[j],storedata[j]);
}
System.out.println(hashMap);

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

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