Java contains方法
我创建了一个充满“状态”的arraylist,但在添加状态后在列表中找不到状态Java contains方法,java,arrays,arraylist,methods,contains,Java,Arrays,Arraylist,Methods,Contains,我创建了一个充满“状态”的arraylist,但在添加状态后在列表中找不到状态 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 {
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)));
}
}
将返回真值。
感谢任何帮助依赖对象的equals()
方法:
更正式地说,返回true当且仅当此列表包含at时
至少一个元素e,使得(o==null?e==null:o.equals(e))
重写它并在状态中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));
public boolean isAnyMatch(列表状态,状态其他){
返回states.stream()
.anyMatch(s->s.getA()==其他.getA()&&
s、 getB()==other.getB()&&
s、 getC()==other.getC())
}
System.out.println(isAnyMatch(节点,新状态(12,0,0));
依赖于对象的equals()
方法:
更正式地说,返回true当且仅当此列表包含at时
至少一个元素e,使得(o==null?e==null:o.equals(e))
重写它并在状态中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));
public boolean isAnyMatch(列表状态,状态其他){
返回states.stream()
.anyMatch(s->s.getA()==其他.getA()&&
s、 getB()==other.getB()&&
s、 getC()==other.getC())
}
System.out.println(isAnyMatch(节点,新状态(12,0,0));
You,你知道如何欢迎你的配对:)You,你知道如何欢迎你的配对:)