Я создаю arrayylist, полный "состояний", но не могу найти состояния в списке после того, как они были добавлены
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;
}
}
Тогда в основном классе
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)));
}
}
Это вернет false, но если я это сделаю
System.out.println(nodes.contains(randomState));
вернет истину. Любая помощь приветствуется




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)).
Переопределите его и hashCode() в классе State, например:
@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));
Вы, знаете, как поприветствовать свои пары :)