2015-07-10 113 views
2

列表中的值在我的程序中覆盖。我想用同一个对象来添加不同的值。值被覆盖,不添加

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]}

回答

5

的问题是,你保持添加的ListMap相同的实例而不进行复制。这是行不通的,因为清除地图外的列表也会清除地图中的列表 - 毕竟它是同一个对象。

list.clear();替换为list = new ArrayList<String>();来解决这个问题。

+0

真正的问题是你是不是实例化循环内的ArrayList集合....因此,当您调用clearlist()时,集合的旧实例变得清晰... 您是否还想重新使用同一个对象进行内存优化? 为什么人们喜欢在这里?第一个答案本身是正确的。 –

+2

@Kannan_SJD *“为什么人们在这里高兴?”*什么?你确定你想在这个答案下发表评论吗? – Tom

2

您必须为您的HashMap中的每个条目实例化一个新的List。 目前,您正在为每个条目添加完全相同的List实例。 与list.clear()相结合,这会产生观测输出。 (唯一的!)列表中的最后条目将定义每个键的输出。

2

亲爱的你在belove线再次与新实例犯错误

list.clear(); 

,而不是这只是初始化列表作为

list = new ArrayList<String>(); 
+0

这是正确的,这是问题,但你能解释为什么这是问题吗?由于OP不知道,这对他有帮助。 – Tom