Why am I removing an element from the wrong ArrayList?

I see some kind of behavior that I can’t understand about, and wondered if anyone would be kind enough to explain exactly what was happening here. This is the code I have.

public class MyClass { ArrayList<String> myList = new ArrayList<String>(); public MyClass() { populate(); removeData(myList); } private void populate() { myList.add("Some data"); myList.add("Some more data"); myList.add("Even more data"); } private void removeData(ArrayList<String> list) { ArrayList<String> temp = new ArrayList<String>(); temp = list; temp.remove("Some data"); } } 

Now for some reason, after running this code, the data is deleted from the ArrayList "myList". Why is this happening, although I only have to delete the data from the variable inside the "removeData" method, and not from the "myList" field?

+5
source share
4 answers
  temp = list; 

Even if you delete inside the method, you still point to the member of the instance, therefore, it can see the changes.

You need to create a new list with these values ​​if you do not want to influence the member of the instance.

+6
source

Change your code to:

 private void removeData(ArrayList<String> list) { ArrayList<String> temp = new ArrayList<String>(list); temp.remove("Some data"); } 

and you will get the desired behavior (although this does not really make much sense). Assigning list to temp does not copy elements in the list, but only assigns a link to the same memory area.

+3
source

Java works with links, so when you assigned temp = list , both variables pointed to the same object. Instead, you want to make a copy of list :

 private void removeData(ArrayList<String> list) { ArrayList<String> temp = new ArrayList<String>(list); // Make a copy temp.remove("Some data"); } 
+1
source
 ArrayList<String> temp = new ArrayList<String>(); temp = list; 

In the first line, you create a new list. Up to this point it is wonderful. But in the next line, you refer to list on temp . Thus, the earlier object referenced by temp will be garbage collected. temp will refer to the same object that was created by Myclass constructor

+1
source

Source: https://habr.com/ru/post/1234213/


All Articles