hashCode(),equals(Object)和compareTo(Class)

A G*_*ore 1 java equals hashmap hashcode compareto

我遵循以下Vertex类,它实现了equals,hashCode和compareTo方法.即使这样,我的HashMap也会返回null.我不知道为什么?

public class Vertex implements Comparable<Vertex> {
    int id;

    public Vertex(int number) {
        id = number;
    }

    public boolean equals(Object other) {
        if (other == null)
            return false;
        else if (other.getClass() != this.getClass())
            return false;
        else {
            Vertex copy = (Vertex) other;
            if (copy.id == this.id)
                return true;
            else
                return false;
        }
    }

    public int hasCode() {
        int prime = 31;
        int smallPrime = 3;
        int hashCode = this.id ^ smallPrime - prime * this.hasCode();
        return hashCode;
    }

    public int compareTo(Vertex other) {
        if (this.id < other.id)
            return -1;
        else if (this.id > other.id)
            return 1;
        else
            return 0;
    }

}
Run Code Online (Sandbox Code Playgroud)

Boz*_*zho 5

你的方法被调用hasCode().让它hashCode()来代替.

我建议使用您的IDE自动生成hashCode()equals(..).这将生成正确的方法(现在你有一个递归调用hashCode())

  • ...然后删除递归调用. (5认同)