gpt4 book ai didi

Java .contains 方法

转载 作者:行者123 更新时间:2023-12-01 17:47:20 25 4
gpt4 key购买 nike

我创建了一个充满“状态”的数组列表,但添加状态后在列表中找不到状态

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() 方法:

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 类中覆盖它和 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));

关于Java .contains 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53675462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com