GeeCON Prague 2014*
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
Author

Does arrayList.contains use == or .equals?

Garrett Smith
Ranch Hand

Joined: Jun 27, 2002
Posts: 401

contains
public boolean contains(Object elem)
Returns true if this list contains the specified element.
Specified by:
contains in interface List
Overrides:
contains in class AbstractCollection
Parameters:
elem - element whose presence in this List is to be tested.
Returns:
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: http://jibbering.com/faq/
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24187
    
  34

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.

Thanks!
Jim Yingst
Wanderer
Sheriff

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
Greenhorn

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
 
GeeCON Prague 2014
 
subject: Does arrayList.contains use == or .equals?