HumparDumpar HumparDumpar - 1 month ago 4x
Java Question

Why does modifying the value of an element in an ArrayList change that of the other?

I want to get the lastElement of 2D arrayList called point and add that last element back to list as a new element with updated Y value and same X value. So basically what i m doing is getting last element of point 2D array, add it at the end of point 2D array but with change to y value to it. But problem is that when i change y value, it also changes the value of the element from which the information was taken.

List<List<Integer>> point = new ArrayList<List<Integer>>();
List<Integer> values= new ArrayList<Integer>();

point.get(0).set(1, 200);

output:[[1, 200], [1, 200]]
Expected output: [[1, 2], [1, 200]]




doesn't do what you think. It adds a reference to the second last element in the arraylist to the last. So when you try to display the value from the last element, it actually fetches the data from the second last values in point and displays that. To modify the data separately, replace the line I pointed out with this:

point.add(new ArrayList<Integer>(values));

So you should separately add two copies of values in the end of point.


point.get(0).set(1, 200); //0 denotes first element. not last

will give you this output:

[[1, 200], [1, 2]]

this should be replaced with

point.get(point.size() - 1).set(1, 200); //last element

Correcting these two errors will give you the expected output.