如何填充HashMap <integer,arraylist <integer =“”>&gt;

时间:2017-02-02 15:45:12

标签: java arraylist

我正在尝试创建一个由ArrayList组成的HashMap作为对象。对于一个不同的键我得到相同的附加arraylist。请在下面找到示例代码

public class Test {

ArrayList<Integer> testlist = new ArrayList<Integer>();
HashMap<Integer, ArrayList<Integer>> testmap = new HashMap<Integer, ArrayList<Integer>>();

public boolean flag = false;

public void setList(int length){
    int key;
    Scanner xyz = new Scanner(System.in);
    for(int i=0;i<length;i++){
        testlist.add(xyz.nextInt());
    }
    System.out.println("Enter the key");
    key=xyz.nextInt();
    setMap(testlist, key);
}

public void setMap(ArrayList<Integer> testlist, int key){
    testmap.put(key, testlist);

    System.out.println(testmap);
}

public static void main(String [] args)
{
    Test t = new Test();
    String str;
    @SuppressWarnings("resource")
    Scanner xyz = new Scanner(System.in);

    int length;
    System.out.println("Enter the length of a list");
    length = xyz.nextInt();

    System.out.println("Populate the list");
    for(int i=0;i<3;i++){
    t.setList(length);      }       


}

}

我收到以下输出

{1 = [10,20,30,40,50,60],2 = [10,20,30,40,50,60]}

但我想要输出如下 {1 = [10,20,30],2 = [40,50,60]}

1 个答案:

答案 0 :(得分:0)

这是因为您创建了ArrayList的一个实例,并将相同的实例放在HashMap的每个键中。

public void setList(int length){
    int key;
    testlist = new ArrayList<Integer>(); // add this and it will ensure that it's always a differen list
    Scanner xyz = new Scanner(System.in);
    for(int i=0;i<length;i++){
        testlist.add(xyz.nextInt());
    }
    System.out.println("Enter the key");
    key=xyz.nextInt();
    setMap(testlist, key); // it's always the same list if you don't create a new one
}

因此,您可能希望为每个条目创建一个新的ArrayList