简体   繁体   中英

ArrayList<String> Object assignment

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.

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM