Created
June 6, 2021 21:41
-
-
Save NikolayGorshkov/3a37cefbb9d8f959e87e30556bf03da7 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test.sample; | |
import java.util.Arrays; | |
import java.util.Objects; | |
/** | |
* How does a record handle arrays in equals and hashCode? | |
* | |
* @author nick | |
* | |
*/ | |
public class ArraysInRecords { | |
record Rec(int[] arr) {} | |
public static void main(String[] args) { | |
int[] arr1 = {1}; | |
int[] arr2 = {1}; | |
System.out.println(arr1.equals(arr2)); // array equals - false | |
System.out.println(Objects.equals(arr1, arr2)); // Objects.equals - false | |
Rec r1 = new Rec(arr1); | |
Rec r2 = new Rec(arr2); | |
System.out.println(Arrays.equals(r1.arr(), r2.arr())); // arrays of the two records have equal content - true | |
System.out.println(r1.equals(r2)); // record built-in equals - false | |
System.out.println(r1.hashCode() == r2.hashCode()); // record built-in hashcode - different values for the two records - false | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment