Java.包含方法

Java .contains method

我创建了一个包含 "states" 的数组列表,但添加后无法在列表中找到状态

public class State {
    int a;
    int b;
    int c;

    public State(int a,int b,int c) {
        super();
        this.a = a;
        this.b = b;
        this.c = c;
    }
}

然后主要class

public class Main {
    static ArrayList<State> nodes = new ArrayList<State>();

    public static void main(String[] args) {
      State randomState = new State(12,0,0);
      nodes.add(randomState);
      System.out.println(nodes.contains(new State(12,0,0)));
    }      
}

这会 return 错误,但如果我这样做

System.out.println(nodes.contains(randomState));

会 return 正确。 感谢任何帮助

List.contains() 依赖对象的 equals() 方法:

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)).

覆盖它并在 State class 中 hashCode() 例如:

@Override
public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof State)) return false;
    State state = (State) o;
    return a == state.a &&
            b == state.b &&
            c == state.c;
}

@Override
public int hashCode() {
    return Objects.hash(a, b, c);
}

或者不用这种方法,自己搜索。
例如:

public boolean isAnyMatch(List<State> states, State other){   
  return states.stream()
               .anyMatch(s -> s.getA() == other.getA() && 
                         s.getB() == other.getB()  && 
                         s.getC() == other.getC() )
}


System.out.println(isAnyMatch(nodes, new State(12,0,0));