January 4, 2017

Java 7 - Implement equals() and hashCode() with java.util.Objects

When using JPA you should implement equals() and hashCode() if you

  • Intend to put instances of persistent classes in a Set.
  • Intend to use reattachment of detached instances.

For JDK 7 and above, you can use the new java.util.Objects class to generate the equals and hash code values.

import java.util.Objects;

public class Fruit {

    private Long id;
    private String name;
    private int weight;

    @Override
    public boolean equals(Object obj) {
        if (obj == this) {
            return true;
        }
        if (!(obj instanceof Fruit)) {
            return false;
        }
        Fruit fruit = (Fruit) obj;
        return Objects.equals(id, fruit.id) && Objects.equals(name, fruit.name) && Objects.equals(weight, fruit.weight);
    }

    @Override
    public int hashCode() {
        return Objects.hash(id, name, weight);
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getWeight() {
        return weight;
    }

    public void setWeight(int weight) {
        this.weight = weight;
    }

}

Test code

Fruit fruit1 = new Fruit();
fruit1.setId(78L);
fruit1.setName("apple");
fruit1.setWeight(35);

Fruit fruit2 = new Fruit();
fruit2.setId(78L);
fruit2.setName("apple");
fruit2.setWeight(35);

assertTrue(fruit1.equals(fruit2));
assertFalse("Not same instance", fruit1 == fruit2);
assertThat(fruit1, is(equalTo(fruit2)));

No comments: