• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to over ride the List.contains() method.

 
Rajkamal Pillai
Ranch Hand
Posts: 445
1
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would like to override the list.contains() to suit my requirements for checking if a particular value object is contained in a list. Right now I implement the Comparable interface and code the compareTo() method in the value object. Is it the right way to go about it?
 
David O'Meara
Rancher
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, you'll want equals() and only need other methods like HashMap or compareTo if the actual List implementation is something like a Hash* or Tree*
 
Rob Spoor
Sheriff
Pie
Posts: 20546
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you use compareTo for checking instead of equals, and a.compareTo(b) == 0 does not imply a.equals(b) for all a and b, then you are breaking the contract for List.contains. That clearly specifies that it should use equals.

However, TreeMap and TreeSet possibly violate the contracts for Map and Set since these also use compareTo (or a Comparator).

You do run a risk though when comparing: contains can take any Object, and that might not be comparable to your elements. In fact, TreeMap (and TreeSet) have the same problem. Consider the following:

Now both System.out.println(map.get(1)); and System.out.println(set.contains(1)); will throw a ClassCastException:
 
Rajkamal Pillai
Ranch Hand
Posts: 445
1
Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Rob,

I used an overridden equals() and hashCode() and it works fine. I guess I got a little confused. I am using an instance of a LinkedList and it works fine for the contains() method.

Cheers,
Raj.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic