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 them from the 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?
resolvent:
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 reference in memory. This may not be the case. To correct this problem, you can override the equals function and let it 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());
}
}
In addition, when you override. Equals, it is recommended that you also override hashcode so that the object can work properly in hash functions such as set or map