Jack
Jack

Reputation: 1

Understanding hashCode(), equals() and toString() in Java

I am beginner in Java and although I have a look at several questions and answers in SO, I am not sure if I completely understand the usage of hashCode(), equals() and toString() in Java. I encountered the following code in a project and want to understand the following issues:

1. Is it meaningful to define these methods and call via super like return super.hashCode()?

2. Where should we defines these three methods? For each entity? Or any other place in Java?

3. Could you please explain me the philosophy of defining these 3 (or maybe similar ones that I have not seen before) in Java?

@Entity
@SequenceGenerator(name = "product_gen", sequenceName = "product_id_seq")
@Table
@Getter
@Setter
@ToString(callSuper = true)
@NoArgsConstructor
public class Product extends BaseEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "product_gen")
    private long id;

    @Override
    public int hashCode() {
        return super.hashCode();
    }

    @Override
    public boolean equals(Object other) {
        return super.equals(other);
    }
}

Upvotes: 1

Views: 6886

Answers (1)

Pradipta Sarma
Pradipta Sarma

Reputation: 1348

  1. toString() method returns the String representation of an Object. The default implementation of toString() for an object returns the HashCode value of the Object. We'll come to what HashCode is. Overriding the toString() is straightforward and helps us print the content of the Object. @ToString annotation from Lombok does that for us. It Prints the class name and each field in the class with its value. The @ToString annotation also takes in configuration keys for various behaviours. Read here. callSuper just denotes that an extended class needs to call the toString() from its parent. hashCode() for an object returns an integer value, generated by a hashing algorithm. This can be used to identify whether two objects have similar Hash values which eventually help identifying whether two variables are pointing to the same instance of the Object. If two objects are equal from the .equals() method, they must share the same HashCode

  2. They are supposed to be defined on the entity, if at all you need to override them.

  3. Each of the three have their own purposes. equals() and hashCode() are majorly used to identify whether two objects are the same/equal. Whereas, toString() is used to Serialise the object to make it more readable in logs.

From Effective Java:

You must override hashCode() in every class that overrides equals(). Failure to do so will result in a violation of the general contract for Object.hashCode(), which will prevent your class from functioning properly in conjunction with all hash-based collections, including HashMap, HashSet, and HashTable.

Upvotes: 3

Related Questions