ArrayList .contains()有时是true,有时是false

Gra*_*esp 2 java equals arraylist hashcode

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

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;
}
Run Code Online (Sandbox Code Playgroud)

在我的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;
Run Code Online (Sandbox Code Playgroud)

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

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());
            }
        }
Run Code Online (Sandbox Code Playgroud)

但是我有另一个类用于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...
    }
Run Code Online (Sandbox Code Playgroud)

但是当我从这里调用方法时,它总是说ArrayList不包含Vertex而且//做某事......永远不会到达.

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

我的错误是什么?

Men*_*ild 6

你的equals() - hashCode() - 实现被破坏了.规范指出,相等的对象必须具有相同的哈希码.但是在你的equals()方法中,你忽略了名字的情况,而hash-method却没有忽略它.

如果您使用基于散列的映射,并且distance.containsKey(vertex)看起来像典型的映射查找,则此行为是相关的,因此我假设您的对象distance是一种Map.

解决方案:使您的hashCode()-method也不区分大小写,或者使您的equals()-method区分大小写.