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?
LinkedList uses the equals method, not Comparable.compareTo. You should override equals (and hashCode) in MyObject to solve the problem.