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. contains() method is used to check whether an element is present in a LinkedList or not. It takes the element as a parameter and returns True if the element is present in the list.
Linked list. A Linked list is a collection of linear data elements. Each element (or node) contains data and reference parts. The data part has the value and the reference part has the address to the next element.
The equals() method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. Syntax: public boolean equals(Object obj)
LinkedList uses the equals method, not Comparable.compareTo. You should override equals (and hashCode) in MyObject to solve the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With