File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes How to over ride the List.contains() method. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "How to over ride the List.contains() method." Watch "How to over ride the List.contains() method." New topic
Author

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

Rajkamal Pillai
Ranch Hand

Joined: Mar 02, 2005
Posts: 443
    
    1

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

Joined: Mar 06, 2001
Posts: 13459

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

Joined: Oct 27, 2005
Posts: 19651
    
  18

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:


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Rajkamal Pillai
Ranch Hand

Joined: Mar 02, 2005
Posts: 443
    
    1

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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to over ride the List.contains() method.
 
Similar Threads
ArrayList.Contains always return true, even the objects are not equal
synchronize on .contains() ?
Loops in a user defined date class
How to make List.contains(Object) work when you write your own .equals function
choosing a data structure