Replacing values for a particular key in treemap changes values for every key

Chhaganlaal :

For some reason when I change a value for a particular key in my tree-map every key value changes for some reason. Here's the code snippet,

ArrayList<Integer> bitor = new ArrayList<>();
TreeMap<Integer, ArrayList> a = new TreeMap<>();
for(int i=0; i<4; i++)
    bitor.add(0);
for(int i=0; i<n; i++)
{
    a.put(i, bitor);
}
System.out.println(a);
for(int i=0; i<n; i++)
{
    x = i;
    for(int j=0; j<n; j++)
    {
        if(x!=j)
        {
            y = j;
            for(int k=0; k<n; k++)
            {
                if(x!=k && y!=k)
                {
                    z = k;
                    System.out.println(a);
                    bitor = a.get(x);
                    if(bitor.get(0)==3)
                        break;
                    System.out.println(1+" "+x+" "+y+" "+z);
                    System.out.flush();
                    bitor.set(0, bitor.get(0)+1);
                    ans = sc.nextInt();
                    if(ans==-1)
                        System.exit(ans);
                    bitor.set(bitor.get(0), ans);
                    a.replace(x, bitor);
                }
                if(bitor.get(0)==3)
                    break;
            }
        }
    }
}

Output image

Only the arraylist value for key=0 was supposed to change but every key-value got changed.

This is kind of weird and I am guessing I am doing a silly mistake.

Louis Wasserman :
for(int i=0; i<n; i++)
{
    a.put(i, bitor);
}

This doesn't do what you think it does. Every key points to the same value. You must create a new bitor, explicitly, for each i.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=113083&siteId=1