列表中的值在我的程序中被覆盖。我想使用同一个对象来添加不同的值。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
public class CommonValue {
static int key = 100;
public static void main(String[] args) throws IOException {
HashMap<Integer, ArrayList<String>> map = new HashMap<Integer, ArrayList<String>>();
ArrayList<String> list = new ArrayList<String>();
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
StringBuffer sBuffer = new StringBuffer();
Scanner scan = new Scanner(System.in);
String choice = null;
do {
System.out.println("enter the how many element to add");
int numOfElement = Integer.parseInt(reader.readLine());
String userInput;
int i = 0;
do {
// adding element in the list
System.out.println("enter the element to add in the list");
userInput = scan.next();
list.add(userInput);
i++;
} while (i < numOfElement);
// adding list in the map with key
map.put(key, list);
System.out.println(map);
list.clear();
// my intial key is 100 and it will incremented when i am going for another key
key++;
System.out.println("do you want to go for next key");
System.out.println("y or n");
choice = scan.next();
} while (choice.equals("y"));
for (Entry<Integer, ArrayList<String>> entry : map.entrySet()) {
key = entry.getKey();
ArrayList<String> value = entry.getValue();
System.out.println("key" + entry.getKey() + ": value " + entry.getValue());
}
}
}
输出:
enter the how many element to add
2
enter the element to add in the list
a
enter the element to add in the list
x
{100=[a, x]}
do you want to go for next key
y or n
y
enter the how many element to add
1
enter the element to add in the list
z
{100=[z], 101=[z]}
do you want to go for next key
y or n
实际上我需要的输出是:
{100=[a,x], 101=[z]}
最佳答案
问题是您不断添加 List
的相同实例到 Map
无需复制。这是行不通的,因为清除 map 外的列表也会清除 map 内的列表 - 毕竟,它是同一个对象。
替换list.clear();
与 list = new ArrayList<String>();
解决这个问题。
关于java - 值被覆盖而不是添加,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31341664/