1

I have two separate objects ArrayList<String> in two separate packages Top and top10. I assign the value of top10 to Top in my activity. And now if I remove an element from Top it also gets removed from top10. I don't know why is this happening? I feel totally dumbfounded. Is there something I don't know about java? Or is it android?

This is my activity code:

ArrayList<String> Top = new ArrayList<String>();          

// ServiceCall is the name of the class where top10 is initialized.

Top = ServiceCall.top10;

System.out.println("top WR: "+ServiceCall.top10);

if(Top.get(0).equals("Please Select")) Top.remove(0);   

System.out.println("top WR: "+ServiceCall.top10);

The second printed out statement has one element less than the one before.

Harsh
  • 487
  • 3
  • 9
  • 29

2 Answers2

2

You are pointing to the same Object.

Top = ServiceCall.top10;

is not creating a new Object, but making a reference to the other one, hence all changes in both pointers will be reflected in the same Object.

You'll have to create a new one passing the other one as parameter:

List<String> Top = new ArrayList<String>(ServiceCall.top10);
Iñigo
  • 12,723
  • 2
  • 31
  • 31
1

You are pointing Top to top10, not creating a new list (your initializer is effectively unused right now, as you are just repointing it to the other list.)

You should do:

ArrayList<String> Top = new ArrayList<String>(ServiceCall.top10);    

This will create a shallow copy.

Dima
  • 23,484
  • 6
  • 56
  • 83