equals and hashCode (course memo)
Java. Whenever we need to compare data classes, we have to implement two methods: equals and hashCode. IntelliJ can auto-generate both.
Implementing equals & hashCode in IntelliJ
Define the data class fully first (properties, getters, setters, constructor) before generating equals/hashCode — if you add a property afterward, you either have to manually update the generated methods or delete and regenerate them.
Steps: put the cursor on a new line at the end of the class, start typing equals, accept IntelliJ's "override equals method" suggestion, click Next through the wizard until it becomes Finish, click Finish. Both methods get generated together.
Result
java
package academy.everyonecodes.java.week7.snippets;
import java.util.Objects;
public class EqualsExample {
private String name;
private int age;
public EqualsExample(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
EqualsExample that = (EqualsExample) o;
return age == that.age &&
Objects.equals(name, that.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}All objects of the class are now compared property by property.