File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Does arrayList.contains use == or .equals? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Does arrayList.contains use == or .equals?" Watch "Does arrayList.contains use == or .equals?" New topic

Does arrayList.contains use == or .equals?

Garrett Smith
Ranch Hand

Joined: Jun 27, 2002
Posts: 401

public boolean contains(Object elem)
Returns true if this list contains the specified element.
Specified by:
contains in interface List
contains in class AbstractCollection
elem - element whose presence in this List is to be tested.
true if the specified element is present; false otherwise.

I guess it uses == and not equals method.

I'm trying to make a cart. If the cart has the product already, I want to increase the number.
Maybe I need a static product.getInstance method...

Sometimes just typing out a question makes me think about it more.

comp.lang.javascript FAQ:
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

It uses equals, not ==. The source comes with the JDK, remember:

[Jess in Action][AskingGoodQuestions]
Garrett Smith
Ranch Hand

Joined: Jun 27, 2002
Posts: 401
Quick answer.

Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Aside from checking the source code, the API for contains() in Collection requires that equals() be used here. So does the API for contains() in List - it's a duplicate of the text in Collection. The API for ArrayList did not bother to mention this fact; however the inherited APIs still apply. So don't forget to check superclasses and superinterfaces when checking the documentation of a class.

"I'm not back." - Bill Harding, Twister
Bill Milligan

Joined: Jan 20, 2004
Posts: 2
If you're having issues with this (I assume you are, from the context), it may behoove you to double check your product.equals() methods. .equals() and .hashcode() are generally overlooked, even by very experienced developers, and frequently don't work the way you believe them to.

- Bill<br /> He Who Codes With Scissors
I agree. Here's the link:
subject: Does arrayList.contains use == or .equals?
It's not a secret anymore!