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"?
 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With