列表中的值在我的程序中覆盖。我想用同一个对象来添加不同的值。值被覆盖,不添加
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());
}
}
}
输出:
进入多少元素添加
进入到列表中添加的元素
一个
进入到列表中添加的元素
x
{100 = [a,x]}
是否要为下一个密钥
y或n
ý
输入多少要添加的元素
输入元件到列表
Ž
{100 = [Z],101 = [Z]}
添加你想要去的下一个关键
y或n
其实我需要的输出是:
{100 = [A,X],101 = [Z]}
真正的问题是你是不是实例化循环内的ArrayList集合....因此,当您调用clearlist()时,集合的旧实例变得清晰... 您是否还想重新使用同一个对象进行内存优化? 为什么人们喜欢在这里?第一个答案本身是正确的。 –
@Kannan_SJD *“为什么人们在这里高兴?”*什么?你确定你想在这个答案下发表评论吗? – Tom