Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ArrayList removeAll() not removing objects

I have the simple ArrayLists of the member class:

ArrayList<Member> mGroupMembers = new ArrayList<>();
ArrayList<Member> mFriends = new ArrayList<>();

Member class:

public class Member {
    private String userUID;
    private String userName;

    public String getUserUID() {
        return userUID;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setUserUID(String userUID) {
        this.userUID = userUID;
    }


}

The ArrayList for friends contains all the users friends. What I simply wish to do is remove from the friends list, group members if present with:

mFriends.removeAll(mGroupMembers);

Yet it does nothing to the mFriends list...

Looking at the log statements, the friend does in fact appear within the mGroupMember list.

Why doesn't this work?

like image 239
Sauron Avatar asked Mar 12 '16 16:03

Sauron


People also ask

How do you remove all objects from an ArrayList?

The Java ArrayList removeAll() method removes all the elements from the arraylist that are also present in the specified collection. The syntax of the removeAll() method is: arraylist. removeAll(Collection c);

What is the difference between ArrayList Clear () and removeAll () methods?

clear() deletes every element from the collection and removeAll() one only removes the elements matching those from another Collection.


1 Answers

How are 2 members determined to be equal? I'm guessing if they have the same ID, you deem them equal, however java wants them to be the exact same reference in memory which may not be the case. To correct for this you can override the equals function to have it return if the ids are equal:

public class Member {
    //..

    @Override
    public boolean equals(Object anObject) {
        if (!(anObject instanceof Member)) {
            return false;
        }
        Member otherMember = (Member)anObject;
        return otherMember.getUserUID().equals(getUserUID());
    }
}

Also when you override .equals it is recommended to also override hashCode so that the objects also work correctly in hashing functions like Set or Map.

like image 157
Kevin DiTraglia Avatar answered Oct 19 '22 14:10

Kevin DiTraglia