Compare objects in LinkedList.contains()

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

    The contains() method uses equals() to determine whether an object is in the list. I suspect your class MyObject does not override the equals() method, and this will be why myList.contains(b) is returning false.

    0 讨论(0)
  • 2020-12-06 12:21

    You need to override the .equals(Oject) and the .hashCode() methods in the MyObject class (hashCode isn't needed for the List... but when you overrite equals the contract says you have to override hashCode).

    Essentially what the contains does is this:

    for(each item in the list)
    {
        if(theCurrentItem.equals(theItemYouAreLookingFor))
        {
            return (true);
        }
    }
    
    return (false);
    

    Take a look at the documentation for Object (for equals and hashCode) here

    Also a really good book to read is Effective Java

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-06 12:30

    Rather than use a LinkedList to search through every element, Have you considered using a new HashSet(Comparator). This will efficiently compare the elements to find a match.

    0 讨论(0)
  • 2020-12-06 12:31

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

    0 讨论(0)
提交回复
热议问题