Java ArrayList Contain always return false although it contain the same value

前端 未结 4 914
挽巷
挽巷 2020-12-02 00:00

This is my Hole Class

class Hole {

public  int a;
public  int b;

Hole(int a, int b) {
    this.a = a;
    this.b = b;
}

So i adding a

4条回答
  •  我在风中等你
    2020-12-02 00:28

    contains() method checks the equal() method on Object while checking .

    You have to ovveride equals method in order to make it work.

    public boolean contains(Object o)

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

    Edit:
    

    If you not ovveriding equals method, Then default Object equals method executes and, as per docs of Equals method

    The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

    So your userInputHole == leftFlowInnerHole is always false as they are pointing to different instances.

    Hence to avoid the default implementation ,you just ovveride that equals in yout class and provide your implementation.

    An efficient equals(Object o) implementation

提交回复
热议问题