ArrayList removeAll() not removing objects

前端 未结 3 778
梦谈多话
梦谈多话 2020-12-10 17:28

I have the simple ArrayLists of the member class:

ArrayList mGroupMembers = new ArrayList<>();
ArrayList mFriends = new Arr         


        
相关标签:
3条回答
  • 2020-12-10 17:45

    As mentioned in the comments, elements from the ArrayList will only be removed if their equals() method returns true. The non-overridden method checks for equality based on reference (i.e. they must be the same object in memory).

    What you probably want is to override equals to be based on the properties of Member, such as in the example below:

    @Override
    public void equals(Object o) {
        if(o == null) {
            return false;
        } else if (!(o instanceof Member)) {
            return false;
        } else {
            return ((Member) o).getUserUID().equals(this.userUID) && ((Member) o).getUserName().equals(this.userName);
        }
    }
    

    In addition, you should override hashCode() when overriding equals() so that when two objects are equal, they have the same hash code. The non-overriden implementation of hashCode is also based on equality by reference.

    0 讨论(0)
  • 2020-12-10 17:52

    You have to know that

    ArrayList#removeAll(Collection)

    makes a call to

    ArrayList#contains(Object)

    which makes a call to

    ArrayList#indexOf(Object)

    which finally calls

    Object#equals


    So if equals is not correctly overridden (following the equals contract rules), you're not getting the correct behaviour.

    0 讨论(0)
  • 2020-12-10 18:02

    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());
        }
    }
    

    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.

    0 讨论(0)
提交回复
热议问题