ArrayList removeAll()不删除对象 [英] ArrayList removeAll() not removing objects

查看:256
本文介绍了ArrayList removeAll()不删除对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有成员类的简单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,以便对象在SetMap之类的哈希函数中也能正常工作.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆