如果我在其中输入新的值和键,Hashmap的值每次都会更新



所以问题是,如果我添加一个新的键&值对到我的hashmap它得到更新,
现在,键是一个类似于和ID的数字,值是一个计数数字的列表,
每个ID都应该有不同的列表,但由于某种原因,它被破坏了
所以我想实现不同的列表值
有一个代码:

HashMap<Integer,List<Integer>> map22 = new HashMap<>();
int countrrr = 0;
List<Integer> asd = new ArrayList<>();
for (int i = 0; i <50; i++) {
asd.add(i);
if (i % 5 == 0) {
countrrr++;
map22.put(countrrr,asd);
System.out.println(asd);
asd.clear();
}
}
System.out.println(map22);

问题的根源是您的代码当前只使用一个List来存储所有结果(因为HashMap.put()不会克隆其参数。(在将结果存储在HashMap中后,您需要创建一个新列表。

类似这样的东西:

HashMap<Integer,List<Integer>> map22 = new HashMap<>();
int countrrr = 0;
List<Integer> asd = new ArrayList<>();
for (int i = 0; i <50; i++) {
asd.add(i);
if (i % 5 == 0) {
countrrr++;
map22.put(countrrr, asd);
System.out.println(asd);
asd = new ArrayList<>();
}
}
System.out.println(map22);

最新更新