gpt4 book ai didi

java - ArrayList .contains() 有时为真,有时为假

转载 作者:行者123 更新时间:2023-12-04 21:27:44 24 4
gpt4 key购买 nike

我正在编写一个模拟图形的简单程序。这就是我实现顶点的方式:(我使用节点这个词来表示邻居,这可能有点令人困惑......)

public class Vertex {

private String name;
private int nodes;

public Vertex(String name) {
this.name = name;
nodes = 0;
}

@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}

@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Vertex other = (Vertex) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equalsIgnoreCase(other.name))
return false;
return true;
}

在我的 Graph 类中,我编写了一个返回特定顶点的邻居(节点)的方法:

public List<Vertex> getNodesOf(Vertex v) {
List<Vertex> nodes = new ArrayList<>();
if (vertices.contains(v)) { //vertices is an ArrayList<Vertex>
// adds all neighbours to nodes...
return nodes;
} else {
Terminal.printLine("Error, " + v.getName() + " does not exist here!");
return nodes;

当我从我的主要方法调用该方法时,它工作正常:

List<Vertex> nodes = g.getNodesOf(new Vertex(input[1]));    //input[1] is a name typed by the user
if (nodes != null) {
for (Vertex node : nodes) {
System.out.println(node.getName());
}
}

但我有另一个类用于 dijkstra 算法来查找最短路径。该算法还需要邻居。这是代码的一部分:

    Vertex nearest = null;
int distanceInt = 9999;
for (Vertex vertex : unvisited) {
if (distance.containsKey(vertex)) {
if (distance.get(vertex) <= distanceInt) {
nearest = vertex;
distanceInt = distance.get(vertex);
}
}
}

if (graph.getNodesOf(nearest).contains(vertex)) {
// do something...
}

但是当我从这里调用该方法时,它总是说 ArrayList 不包含 Vertex 并且//do something... 将永远无法到达。

我用 eclipse 覆盖了 equals 和 hashcode 方法,所以我想,这不是问题所在。

我的错误是什么?

最佳答案

您的 equals()-hashCode()-实现被破坏了。 spec表示相等的对象必须具有相等的哈希码。但是在您的 equals() 方法中您忽略了名称的大小写,而哈希方法不会忽略它。

如果您使用基于散列的 map ,此行为是相关的,并且 distance.containsKey(vertex) 看起来像典型的 map 查找,所以我假设您的 distance- object 是一种 Map

解决方案:让您的hashCode() 方法也区分大小写,或者让您的equals() 方法区分大小写。

关于java - ArrayList .contains() 有时为真,有时为假,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35850934/

24 4 0