如果我在其中放入新值和键,Hashmap 值每次都会更新
Hashmap's values update every time if I put new values & keys in it
所以问题是,如果我将一个新的键值对添加到我的哈希图中,它就会更新,
现在,键是一个数字和 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);
问题的根源是您的代码目前仅使用一个列表来存储所有结果(因为 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);
所以问题是,如果我将一个新的键值对添加到我的哈希图中,它就会更新,
现在,键是一个数字和 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);
问题的根源是您的代码目前仅使用一个列表来存储所有结果(因为 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);