A Gore
A Gore

Reputation: 1900

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

I've following the following Vertex class and it implements equals, hashCode and compareTo method. Even then my HashMap returns null. I don't know why?

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

}

Upvotes: 1

Views: 2272

Answers (3)

Peter Lawrey
Peter Lawrey

Reputation: 533492

Try this based on what Integer does. Note: the use of @Override would have shown you were overriding the wrong method.

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

Upvotes: 0

sanbhat
sanbhat

Reputation: 17622

Also, in your equals() method

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

can be changed to

else if(!(other instanceof Vertex))
        return false;

Upvotes: 0

Bozho
Bozho

Reputation: 597046

Your method is called hasCode(). Make it hashCode() instead.

I'd suggest using your IDE to automatically generate hashCode() and equals(..). That will generate the proper methods (right now you have a recursive call in hashCode())

Upvotes: 5

Related Questions