Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I removing an element from the wrong ArrayList?

Tags:

java

arraylist

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"?

like image 675
Wodlo Avatar asked Oct 21 '15 17:10

Wodlo


1 Answers

 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.

like image 145
Suresh Atta Avatar answered Nov 15 '22 05:11

Suresh Atta