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

后端 未结 9 1201
伪装坚强ぢ
伪装坚强ぢ 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条回答
  •  孤城傲影
    2020-11-22 11:07

    class Thing {  
        public int value;  
    
        public Thing (int x) {
            value = x;
        }
    
        equals (Thing x) {
            if (x.value == value) return true;
            return false;
        }
    }
    

    You must write:

    class Thing {  
        public int value;  
    
        public Thing (int x) {
            value = x;
        }
    
        public boolean equals (Object o) {
        Thing x = (Thing) o;
            if (x.value == value) return true;
            return false;
        }
    }
    

    Now it works ;)

提交回复
热议问题