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
或Map
之类的哈希函数中也能正常工作.
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屋!