-1

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.

Cœur
  • 37,241
  • 25
  • 195
  • 267
CodeNoob
  • 411
  • 1
  • 7
  • 24

2 Answers2

0

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.

rlinden
  • 2,053
  • 1
  • 12
  • 13
  • Thanks this helped. Is the colon put there intentional? – CodeNoob Jun 13 '12 at 21:15
  • I didn't compile - the code should be ckecked. Looking back, the correct syntax would be for (String s : olderList) so the colon is there to stay. – rlinden Jun 14 '12 at 02:24
0

You must create a new list and clone every element. If you call

olderList.clone()

it will give you a shallow copy (i.e. a new list with references to the objects of the first list). You must do something like this:

for(String name : olderList){
    newList.add(name.clone());
}

reference: java api Cloneable, Object.clone()

ElderMael
  • 7,000
  • 5
  • 34
  • 53