How does a ArrayList's contains() method evaluate objects?

后端 未结 9 1204
伪装坚强ぢ
伪装坚强ぢ 2020-11-22 10:32

Say I create one object and add it to my ArrayList. If I then create another object with exactly the same constructor input, will the contains() me

9条回答
  •  萌比男神i
    2020-11-22 10:57

    Just wanted to note that the following implementation is wrong when value is not a primitive type:

    public class Thing
    {
        public Object value;  
    
        public Thing (Object x)
        {
            this.value = x;
        }
    
        @Override
        public boolean equals(Object object)
        {
            boolean sameSame = false;
    
            if (object != null && object instanceof Thing)
            {
                sameSame = this.value == ((Thing) object).value;
            }
    
            return sameSame;
        }
    }
    

    In that case I propose the following:

    public class Thing {
        public Object value;  
    
        public Thing (Object x) {
            value = x;
        }
    
        @Override
        public boolean equals(Object object) {
    
            if (object != null && object instanceof Thing) {
                Thing thing = (Thing) object;
                if (value == null) {
                    return (thing.value == null);
                }
                else {
                    return value.equals(thing.value);
                }
            }
    
            return false;
        }
    }
    

提交回复
热议问题