java - 值被覆盖而不是添加

标签 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());
        }
    }
} 

输出:

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/

相关文章:

php - 调用父类方法

c++ - 尝试调用默认构造函数时没有匹配的构造函数

ios - UIView 类对父 View Controller 有太多委托(delegate)方法?

java - 静态实用方法不是这种情况下的最佳方法吗?

java - 不支持的类 : com. mediatek.common.telephony.IOnlyOwnerSimSupport

java - 衡量 Java 应用程序的性能

javascript - FUNCTIONS 的继承正在成为一场噩梦

python - Python 中的对象类型转换(设计建议)

java - 偏向锁定设计决策

java - 如何解决java鼠标和键盘事件之间的冲突?