簡體   English   中英

ArrayList .contains()有時為true,有時為false

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

我正在編寫一個簡單的程序來模擬圖形。 這是我實現頂點的方式:(我將單詞結點用於鄰居,這可能有點令人困惑。)

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不包含頂點,並且//做某事...永遠不會到達。

我用Eclipse覆蓋了equals和hashcode方法,所以我認為這不是問題。

我的錯是什么?

您的equals()-hashCode()-實現已損壞。 規范說,相等的對象必須具有相等的哈希碼。 但是在equals()方法中,您會忽略名稱的大小寫,而在哈希方法中則不會忽略名稱。

如果您使用基於哈希的地圖,並且distance.containsKey(vertex)看起來像是典型的地圖查找,那么此行為是相關的,因此我假設您的distance object是Map的一種。

解決方案:使hashCode()方法也區分大小寫,或者使equals()方法區分大小寫。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM