Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare objects in LinkedList.contains()

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?

like image 670
Eric Avatar asked Feb 14 '09 21:02

Eric


People also ask

How do you check if a linked list contains an item?

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.

Does linked list have contains?

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.

How do you compare two objects?

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)


1 Answers

LinkedList uses the equals method, not Comparable.compareTo. You should override equals (and hashCode) in MyObject to solve the problem.

like image 121
Brett Daniel Avatar answered Sep 28 '22 02:09

Brett Daniel