Hashcode and equals

后端 未结 7 2455
死守一世寂寞
死守一世寂寞 2020-11-30 14:00

equals and hashCode method must be consistent, which means that when two objects are equal according to equals method their hash

7条回答
  •  广开言路
    2020-11-30 14:53

    First, in that line, you need to change Hashvalue to HashValue, since your class is actually called HashValue.

    Then, uncommenting the line gives you this:

    public boolean equals(Object oo) {
        if(oo instanceof HashValue)
            HashValue hh = (HashValue)oo;
    
        if (this.x==hh.x) {
            return true;
        } else {
            return false;
        }
    }
    

    There are a few things wrong with this:

    1. This doesn't compile because hh isn't in scope when you end up using it.

    2. The first if statement should either make sure that the function doesn't run at all when you compare two things that aren't HashValues (i.e. throw an exception), or it should return false because HashValues are never equal to other types of objects. I generally prefer returning false to throwing an exception.

    3. The second if statement is redundant, because you're just returning what the condition evaluates to.

    Rework your method like this:

    public boolean equals(Object oo) {
        if(!(oo instanceof Hashvalue)) {
            return false;
        }
    
        HashValue hh = (HashValue)oo;
        return (this.x == hh.x);
    }
    

    This isn't quite right, either. To make sure that all equal objects have the same hash code, you have to override hashCode() in HashValue, and you must make sure that it lives up to the guarantee. Here, you could just add this:

    // inside HashValue
    int hashCode() {
        return x;
    }
    

    The implementation is trivial because your object is just a wrapper around an int. You'll need to think harder about this as your objects get more sophisticated.

提交回复
热议问题