Java – ArrayList removeall() does not delete objects
I have simple ArrayLists for member classes:
ArrayList<Member> mGroupMembers = new ArrayList<>(); ArrayList<Member> mFriends = new ArrayList<>();
Membership:
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 users' friends All I want to do is delete from my friends list, if any, group members:
mFriends.removeAll(mGroupMembers);
However, it has no effect on the mFriends list
Check the log statement, and the friend does appear in the mgroupmember list
Why doesn't it work?
Solution
How to determine that two members are equal? I guess they have the same ID. you think they are the same, but Java wants them to be exactly the same references in memory. This may not be the case To correct this problem, you can override the equals function to return when 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 overwrite When equals, it is also recommended to override hashcode so that the object can work normally in hash functions such as set or map