Magnus
Magnus

Reputation: 728

My ArrayList is emptied after I call an apparently irrelevant method

This is my method:

public boolean checkIfFriend(Coin coin){
    ArrayList <int []> testCoordinates = new ArrayList <int[]>();
    testCoordinates = this.coordinates; //I copy my ArrayList <Coin> "coordinates" into another ArrayList, "testCoordinates".
    testCoordinates.retainAll(coin.getCoordinates()); //I remove all elements from "testCoordinates" that do not exist in the ArrayList supplied as argument.
    if (testCoordinates.size() > 1){ //On this line, "this.coordinates" has been emptied for all elements. Why?
        return true;
    }
    return false;
}

After I call the "retainAll"-method, "this.coordinates" has 0 elements in it, whereas it had 29 before.

I suspect that I might have misunderstood something about either ArrayList declarations or the retainAll-method. I don't get why "this.coordinates" is emptied after I call the "retainAll"-method.

Thanks for all help!

Upvotes: 1

Views: 46

Answers (2)

copeg
copeg

Reputation: 8348

Your code does not copy the List, but just references the original. To copy, use the addAll method to the testCoordinates (or the appropriate constructor) rather than assigning it to this.coordinates

ArrayList <int []> testCoordinates = new ArrayList <int[]>(this.coordinates);
testCoordinates.retainAll(...);

Upvotes: 1

rgettman
rgettman

Reputation: 178253

This line does not make a copy of the ArrayList.

testCoordinates = this.coordinates;

It assigns testCoordinates to refer to the same object that this.coordinates refers to. You have two variables referring to the same object, so operations on either reference affect the same object. So, emptying the ArrayList via retainAll affects the only ArrayList object, and the changes are visible through both references to it.

To make a copy, you must create a new object. Replace this:

testCoordinates = this.coordinates;

with this:

testCoordinates = new ArrayList<int[]>(this.coordinates);

Upvotes: 5

Related Questions