• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Does arrayList.contains use == or .equals?

 
Garrett Smith
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
It uses equals, not ==. The source comes with the JDK, remember:
 
Garrett Smith
Ranch Hand
Posts: 401
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Quick answer.

Thanks!
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Bill Milligan
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic