Compare objects in LinkedList.contains()

后端 未结 6 1727
梦谈多话
梦谈多话 2020-12-06 12:00

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

        
6条回答
  •  死守一世寂寞
    2020-12-06 12:28

    ( a == b ) == true
    

    Did you mean a.equals(b) and b.equals(a) return true? This is not the same as a check for reference equality, nor a check for a.compareTo(b) == 0.

    LinkedList.contains() uses equals(), so you have to make sure that the method has been implemented correctly. equals() should also be consistent with compareTo(), though this is not strictly necessary. If you're using a hash-based data structure (e.g. HashSet), you must ensure that hashCode() is implemented correctly.

提交回复
热议问题