• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ArrayList.Contains always return true, even the objects are not equal

 
Jaykiran Teraiya
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi All,

I am using an ArrayList to store my CustomQuery objects. I am using .contains(customQuery) to compare weather the object is already present or not? If it's not there I am adding the object to the list.

The problem is list.contains(customQuery) always return false, even if the objects are equal(i.e. their id's are equal). I've also overrided .equals() and .hascode() method in my CustomQuery class.




Any help would be highly appriciated.

Thanks
Jay
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What will happen if you use equals() method instead of using == in checking the customerQueryId?
 
Jaykiran Teraiya
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks, Worked like a charm..
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And Welcome to JavaRanch!
 
Jaykiran Teraiya
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you for warm welcome.
 
Rob Spoor
Sheriff
Pie
Posts: 20545
56
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Two things:

1) what will happen if I pass a String into the equals method? It will certainly compile.
2) do you really need a List? A Set makes sure of uniqueness; if the order is important then a LinkedHashSet will work as well.
 
Jaykiran Teraiya
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
my first choice was to use a Set, but I need to interact with other API and it accepts list as it's parameter. If I use set I need to convert set into list , so to avoid that conversion I used List.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic