Compare objects in LinkedList.contains()

后端 未结 6 1733
梦谈多话
梦谈多话 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:23

    The documentation for the contains method is as follows:

    Returns true if this collection contains the specified element. More formally, returns true if and only if this collection contains at least one element e such that (o==null ? e==null : o.equals(e)).

    Therefore, you need to override the MyObject's equals(Object o) method.

    So for your example:

    public class MyObject {
      String myVal;
    
      public boolean equals(Object o ) {
        return ((MyObject)o).myVal.equals(myVal);
      }
    }
    

    You do not need to implement anything with the Comparable interface.

提交回复
热议问题