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?
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: