值被覆盖而不是添加

Jan*_*amu 3 java oop

列表中的值覆盖在我的程序中.我想使用相同的对象来添加不同的值.

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());
        }
    }
} 
Run Code Online (Sandbox Code Playgroud)

输出:

输入要添加 的元素
2
要在列表中 输入要添加的元素
a 要在列表中
输入要添加的元素
x
{100 = [a,x]}
是否要转到下一个键
y或者n
y
输入如何要添加的多个元素
1
在列表中输入要添加的元素
z
{100 = [z],101 = [z]}
是否要使用下一个键
y或n

实际上我需要的输出是:

{100 = [a,x],101 = [z]}

das*_*ght 6

问题是,你不断增加的同一个实例ListMap不制作副本.这不起作用,因为清除地图外的列表也会清除地图中的列表 - 毕竟,它是同一个对象.

替换list.clear();list = new ArrayList<String>();以解决此问题.

  • @Kannan_SJD*"为什么人们在这里投票?"*什么?你确定要在这个答案下发表评论吗? (2认同)