ArrayList removeAll() not removing objects

前端 未结 3 780
梦谈多话
梦谈多话 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 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.

提交回复
热议问题