Reputation: 937
I am seeing some behaviour that I can't quite make sense of and was wondering if someone would be kind enough to explain exactly what is going on here. This is the code I currently 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 I run this code, data is being removed from the ArrayList "myList". Why is this happening even though I am only supposed to be removing data from a variable inside the method "removeData" and not from the field "myList"?
Upvotes: 5
Views: 92
Reputation: 3795
ArrayList<String> temp = new ArrayList<String>();
temp = list;
In the first line you are creating new list. Till that point its fine. But in the next line you are referring list
to temp
. So earlier object to which temp
was referring will be garbage collected temp
will be referring to the same object which was created Myclass
constructor
Upvotes: 1
Reputation: 1849
Java works with references, 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");
}
Upvotes: 1
Reputation: 679
Change your code to:
private void removeData(ArrayList<String> list) {
ArrayList<String> temp = new ArrayList<String>(list);
temp.remove("Some data");
}
and you'll get your desired behaviour (though it doesn't really make much sense). Assigning list
to temp
does not copy the items in the list, but assigns just a reference to the same area of memory.
Upvotes: 3
Reputation: 122026
temp = list;
Even though you are removing inside the method, you are still pointing to a instance member, hence it can see the changes.
You need to create a new list with that values if you don't want to affect the instance member.
Upvotes: 6