0

I have many classes that implement a common interface. I use a definition like Array List mytypes, and add objects of that type to the ArrayList. Now i want to use contains method of the ArrayList class to see if this List contains a class i am adding.

If I implement hashcode and equals on the classes will the contains method know if a certain object already is in the ArrayList or not?

1
  • That depends on the ArrayList implementation. Commented Mar 6, 2012 at 14:28

3 Answers 3

2

from List.contains():

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

So basically hashCode() is not relevant here, only equals()

EDIT: [better explicit then implicit], as mentioned in comments by @aiobee, equals() still needs to be overriden - according to the contract - but it will not have effect on the value returned by contains()

Sign up to request clarification or add additional context in comments.

2 Comments

hashCode should still, according to the contract, be overridden as the OP says.
@aioobe: yes, it does, I fully agree on this - but it is not relevant to the return value of contains(). Anyway, I added it to the answer, since it is indeed woths mentioning explicitly.
1

ArrayList.contains won't use hashCode, but it will use equals, as documented:

Returns true if this list contains the specified element. More formally, returns true if and only if this list contains at least one element e such that (o==null ? e==null : o.equals(e)).

(This won't check whether "this class" is already in the list - it will check whether an equal object is in the list.)

2 Comments

But The type of the ArrayList is an Interface. Will the JVM call the equals method on the class that implements the Interface ????
@user365019: Yes, just as it's documented.
1

Implementing hashCode is not useful for that purpose but it is a goog practice to override both equals and hashCode simultaneously.

Yes, it will work, that is the purpose of the contains method.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.