Koray Tugay
Koray Tugay

Reputation: 23844

Equal object in Java

So this is from Head First Java (page 563)

The default behaviour of hashCode() is to generate a unique integer for each object on the heap. So if you don’t override hashCode() in a class, no two objects of that type can EVER be considered equal.

But a simple Test will disprove this I think.

public class Song {

    private String name;

    public Song(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }


    @Override
    public boolean equals(Object obj) {
        Song objectSong = (Song) obj;
        return this.getName().equals(objectSong.getName());
    }

}

Well this will return true:

Song songA = new Song("A","B");
Song songB = new Song("A","C");

System.out.println(songA.equals(songB));

Am I missing something? What is it that the book is trying to tell me?

Upvotes: 0

Views: 145

Answers (3)

Sotirios Delimanolis
Sotirios Delimanolis

Reputation: 280179

The default behaviour of hashCode() is to generate a unique integer for each object on the heap. So if you don’t override hashCode() in a class, no two objects of that type can EVER be considered equal.

You're misinterpreting. The author isn't saying that a method (that's all equals and hashCode are) can't return true for two different objects. They're saying that semantically two objects should not be considered equal if the result of their hashCode isn't equal. They are describing how hashCode should be used. If you use it differently, you may get weird and unexpected results.

Upvotes: 2

Hugo Sousa
Hugo Sousa

Reputation: 1936

In Java, every object has access to the equals() method because it is inherited from the Object class. However, this default implementation just simply compares the memory addresses of the objects. You can override the default implementation of the equals() method defined in java.lang.Object. If you override the equals(), you MUST also override hashCode(). Otherwise a violation of the general contract for Object.hashCode will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections.

Source: http://www.xyzws.com/javafaq/why-always-override-hashcode-if-overriding-equals/20 (take a look at it, it has good examples).

Conclusion: you only need to override equals for a simple comparison. However, you SHOULD also override hashCode for other aspects, such as hash based collections.

Upvotes: 0

NimChimpsky
NimChimpsky

Reputation: 47300

You need to override hashcode so that the class behaves as expected with hashcode based collections (and anything else).

For example what happens if you put your song in a HashSet, and then try to put another one in ?

You should always override Hashcode if you override equals, and vice versa. Make sure they are consistent.

(josh bloch effective java, is a good starting point)

Upvotes: 1

Related Questions