1

私は次の 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;
    }

}
4

3 に答える 3

5

あなたのメソッドは と呼ばれhasCode()ます。hashCode()代わりに作ってください。

hashCode()IDE を使用してとを自動的に生成することをお勧めしますequals(..)。これにより、適切なメソッドが生成されます (現在、 に再帰呼び出しがありますhashCode()) 。

于 2013-05-06T07:28:46.757 に答える
0

Integer の動作に基づいてこれを試してください。注: を使用すると@Override、間違ったメソッドをオーバーライドしていることがわかります。

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

    @Override
    public boolean equals(Object other){
        if(!(other instanceof Vertex)) return false;

        return ((Vertex)other).id == id;
    }

    @Override
    public int hashCode() { return id; }
}
于 2013-05-06T07:34:28.300 に答える
0

また、あなたのequals()方法では

else if(other.getClass()!=this.getClass())
        return false;

に変更できます

else if(!(other instanceof Vertex))
        return false;
于 2013-05-06T07:30:12.717 に答える