简体   繁体   English

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

[英]ArrayList .contains() sometimes true, sometimes false

I´m writing a simple Program which simulates a graph. 我正在编写一个简单的程序来模拟图形。 This is how i implement a vertex: ( i used the word nodes for neighbours, thats a little confusing maybe..) 这是我实现顶点的方式:(我将单词结点用于邻居,这可能有点令人困惑。)

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;
}

In my Graph class I wrote a method which returns the neighbours(nodes) of a specific vertex: 在我的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;

When I call that method from my main method, it works fine: 当我从主方法调用该方法时,它可以正常工作:

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());
            }
        }

But I have another class for the dijkstra-algorithm to find the shortest path. 但是我有另一种关于dijkstra算法的课程来找到最短的路径。 this algorithm also needs the neighbours. 该算法也需要邻居。 this is a part of the code: 这是代码的一部分:

    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...
    }

But when i call the method from here, it always says that the ArrayList doesn´t contain the Vertex and the //do something... will never be reached. 但是,当我从此处调用该方法时,它总是表示ArrayList不包含顶点,并且//做某事...永远不会到达。

I overrided the equals and hashcode method with eclipse, so i thought, this was not the problem. 我用Eclipse覆盖了equals和hashcode方法,所以我认为这不是问题。

What´s my mistake? 我的错是什么?

Your equals()-hashCode()-implementation is broken. 您的equals()-hashCode()-实现已损坏。 The spec says that equal objects must have equal hash-codes. 规范说,相等的对象必须具有相等的哈希码。 But in your equals()-method you ignore the case of names while the hash-method does not ignore it. 但是在equals()方法中,您会忽略名称的大小写,而在哈希方法中则不会忽略名称。

This behaviour is relevant if you use hash-based maps, and distance.containsKey(vertex) looks like a typical map-lookup so I assume that your distance -object is a kind of Map . 如果您使用基于哈希的地图,并且distance.containsKey(vertex)看起来像是典型的地图查找,那么此行为是相关的,因此我假设您的distance object是Map的一种。

Solution: Make your hashCode() -method also case-insensitive, or make your equals() -method case-sensitive. 解决方案:使hashCode()方法也区分大小写,或者使equals()方法区分大小写。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 ArrayList.contains()有时在等号字符串上返回false - ArrayList.contains() return false on equals strings sometimes Hibernate布尔值true_false在MySql中产生一个字符……有时? - Hibernate boolean true_false yields a char in MySql… sometimes? isUserInRole有时会返回false - isUserInRole sometimes returns false ArrayList.addAll(ArrayList)抛出SOMETIMES UnsupportedOperationException - ArrayList.addAll(ArrayList) throws SOMETIMES UnsupportedOperationException 用 GSON 解析 JSON,object 有时包含列表有时包含 ZA8CFDE6331BD59EB2AC96F8911C4B6 - Parsing JSON with GSON, object sometimes contains list sometimes contains object 使用多线程将元素添加到 ArrayList 时,有时会给出 ConcurrentModificationException,有时不会? - While adding element into ArrayList using Multithreading, sometimes it give ConcurrentModificationException and sometimes not? 创建后,JGit LogCommand有时可调用为false - JGit LogCommand sometimes callable is false after creation SSH 使用 jschexception verify false 有时会失败 - SSH using jschexception verify false sometimes fails 虽然真实循环有时会中断 - While-true loop lopping sometimes HttpURLConnection getInputStream() 有时包含响应标头 - HttpURLConnection getInputStream() sometimes contains response headers
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM