I want to be able to have LinkedList.contains() return true for a custom comparator.
Suppose that I have 1 LinkedList and 2 objects
LinkedList<MyObject> myList = new LinkedList<MyObject>();
MyObject a = new MyObject("HELLO");
MyObject b = new MyObject("HELLO");
Technicaly, both objects are identical in terms of comparison (MyObject implements Comparable)
( a == b ) == true
however, when I do the following, myList does not return true for myList.contains(b)
myList.add(a)
myList.contains(b) // == false
I think its because contains will check object reference and see that a and b are 2 distinct objects. Is there any way I can make it so I don't have to extend LinkedList to compare those objects?
Did you mean
a.equals(b)
andb.equals(a)
returntrue
? This is not the same as a check for reference equality, nor a check fora.compareTo(b) == 0
.LinkedList.contains()
usesequals()
, so you have to make sure that the method has been implemented correctly.equals()
should also be consistent withcompareTo()
, though this is not strictly necessary. If you're using a hash-based data structure (e.g.HashSet
), you must ensure thathashCode()
is implemented correctly.The
contains()
method usesequals()
to determine whether an object is in the list. I suspect your classMyObject
does not override theequals()
method, and this will be whymyList.contains(b)
is returningfalse
.LinkedList uses the equals method, not Comparable.compareTo. You should override equals (and hashCode) in MyObject to solve the problem.
You need to override the .equals(Oject) and the .hashCode() methods in the MyObject class (hashCode isn't needed for the List... but when you overrite equals the contract says you have to override hashCode).
Essentially what the contains does is this:
Take a look at the documentation for Object (for equals and hashCode) here
Also a really good book to read is Effective Java
The documentation for the contains method is as follows:
Therefore, you need to override the MyObject's equals(Object o) method.
So for your example:
You do not need to implement anything with the Comparable interface.
Rather than use a LinkedList to search through every element, Have you considered using a new HashSet(Comparator). This will efficiently compare the elements to find a match.