我创建了一个充满“状态”的数组列表,但在添加状态后在列表中找不到状态
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));
会返回true。任何帮助表示赞赏
List.contains()
依赖于equals()
对象的方法:
更正式地,当且仅当此列表包含至少一个元素 e 时才返回 true
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));
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句