0

Does ArrayList.get(index) return only the value of the element at index or a pointer to this element? I ask this because this doesn't perform as I expect it to

List<List<Integer>> myList; 
myList = new ArrayList<>(Collections.nCopies(n, new ArrayList<>()));
           .
           .
           .
List tempList = this.myList.get(x);
tempList.add(i);
this.myList.set(i,tempList);

Instead of adding an element to the array at index x, and storing the new list at index i, it is appending the element at both spots so instead of a list increasing in size, I get n times the last element

Kevin Martin
  • 33
  • 1
  • 6

1 Answers1

1

You are looking at the wrong place.

There is absolutely nothing wrong with this code:

List tempList = this.myList.get(x);
tempList.add(i);
this.myList.set(i,tempList);

except that it can be abbreviated to this:

List tempList = this.myList.get(x);
tempList.add(i);

(and except that you are using List, which is a raw data type, which also means that you do not have warnings enabled, but that's another story.)

Your problem is here:

myList = new ArrayList<>(Collections.nCopies(n, new ArrayList<>()));

If you look at the implementation of Collections.nCopies() you will see that it internally uses a special list which contains only one element, the element that you gave it, and no matter which index you request, it returns to you that same original element.

So, you do not have n lists to begin with; you only have one list.

Mike Nakis
  • 56,297
  • 11
  • 110
  • 142