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

后端 未结 9 1018
伪装坚强ぢ
伪装坚强ぢ 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 ;)

    0 讨论(0)
  • 2020-11-22 11:14

    Other posters have addressed the question about how contains() works.

    An equally important aspect of your question is how to properly implement equals(). And the answer to this is really dependent on what constitutes object equality for this particular class. In the example you provided, if you have two different objects that both have x=5, are they equal? It really depends on what you are trying to do.

    If you are only interested in object equality, then the default implementation of .equals() (the one provided by Object) uses identity only (i.e. this == other). If that's what you want, then just don't implement equals() on your class (let it inherit from Object). The code you wrote, while kind of correct if you are going for identity, would never appear in a real class b/c it provides no benefit over using the default Object.equals() implementation.

    If you are just getting started with this stuff, I strongly recommend the Effective Java book by Joshua Bloch. It's a great read, and covers this sort of thing (plus how to correctly implement equals() when you are trying to do more than identity based comparisons)

    0 讨论(0)
  • 2020-11-22 11:15

    It uses the equals method on the objects. So unless Thing overrides equals and uses the variables stored in the objects for comparison, it will not return true on the contains() method.

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