Search code examples
listref

Copy list objects value not reference


I'm try to create a new list object. I set the new object to an old existing object.

List<string> names = new List<string>();
names = olderList;

The problem I have is that the names list points to the olderList as a result when olderList changes, names changes too. I tried copying the values with a foreach but it's still doing the same thing, refering to the olderList.


Solution

  • When you make an assignment in Java, you copy the reference, not the content. Therefore, names will point to the same memory address that olderList does.

    When you copy all the values, you do the same thing - you are assigning to the names list another reference to each String stored in the olderList.

    An idea that might solve your problem is to use the foreach but instead of adding each element, creating a new String that is a copy of the old one. It would be something like this:

    names=new List<String>();
    foreach (String s: olderList) {
      names.add(new String(s));
    }
    

    Check the constructor I used and its meaning at Oracle's reference site.