Skip to content

Instantly share code, notes, and snippets.

@NikolayGorshkov
Created June 6, 2021 21:41
Show Gist options
  • Save NikolayGorshkov/3a37cefbb9d8f959e87e30556bf03da7 to your computer and use it in GitHub Desktop.
Save NikolayGorshkov/3a37cefbb9d8f959e87e30556bf03da7 to your computer and use it in GitHub Desktop.
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