[BAEL-6253] record equals hashcode (#13958)

* [BAEL-6253] records equals and hashcode

* [BAEL-6253] records equals and hashcode

* [BAEL-6253] records equals and hashcode test case

---------

Co-authored-by: Bhaskar <bhaskar.dastidar@freshworks.com>
This commit is contained in:
Bhaskar Ghosh Dastidar
2023-05-06 21:58:20 +05:30
committed by GitHub
parent 7123ae8ad7
commit ce79066afc
5 changed files with 94 additions and 0 deletions
@@ -0,0 +1,26 @@
package com.baeldung.equalshashcoderecords;
import java.util.Objects;
record Movie(String name, Integer yearOfRelease, String distributor) {
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other == null) {
return false;
}
Movie movie = (Movie) other;
if (movie.name.equals(this.name) && movie.yearOfRelease.equals(this.yearOfRelease)) {
return true;
}
return false;
}
@Override
public int hashCode() {
return Objects.hash(name, yearOfRelease);
}
}
@@ -0,0 +1,5 @@
package com.baeldung.equalshashcoderecords;
public record Person(String firstName, String lastName, String SSN, String dateOfBirth) {
};
@@ -0,0 +1,30 @@
package com.baeldung.equalshashcoderecords;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotEquals;
import org.junit.Test;
public class CustomRecordEqualsHashCode {
@Test
public void givenTwoRecords_whenDefaultEquals_thenCompareEquality() {
Person robert = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
Person mike = new Person("Mike", "Adams", "ABJDJ2883", "2001-01-02");
assertNotEquals(robert, mike);
}
@Test
public void givenTwoRecords_hashCodesShouldBeSame() {
Person robert = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
Person robertCopy = new Person("Robert", "Frost", "HDHDB223", "2000-01-02");
assertEquals(robert.hashCode(), robertCopy.hashCode());
}
@Test
public void givenTwoRecords_whenCustomImplementation_thenCompareEquality() {
Movie movie1 = new Movie("The Batman", 2022, "WB");
Movie movie2 = new Movie("The Batman", 2022, "Dreamworks");
assertEquals(movie1, movie2);
assertEquals(movie1.hashCode(), movie2.hashCode());
}
}