ArrayList removeAll() 不删除对象 [英] ArrayList removeAll() not removing objects
问题描述
我有成员类的简单 ArrayLists:
I have the simple ArrayLists of the member class:
ArrayList<Member> mGroupMembers = new ArrayList<>();
ArrayList<Member> mFriends = new ArrayList<>();
会员等级:
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;
}
}
朋友的 ArrayList 包含所有用户朋友.我只想做的是从朋友列表中删除,如果有群组成员:
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);
然而它对 mFriends
列表没有任何作用...
Yet it does nothing to the mFriends
list...
查看日志语句,朋友确实出现在 mGroupMember
列表中.
Looking at the log statements, the friend does in fact appear within the mGroupMember
list.
为什么这不起作用?
推荐答案
如何确定 2 个成员相等?我猜他们是否具有相同的 ID,您认为它们相等,但是 java 希望它们在内存中成为完全相同的引用,但情况可能并非如此.要对此进行纠正,您可以覆盖 equals
函数以使其在 id 相等时返回:
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());
}
}
此外,当您覆盖 .equals
时,建议也覆盖 hashCode
以便对象在散列函数中也能正常工作,例如 Set
或地图
.
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
.
这篇关于ArrayList removeAll() 不删除对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!