Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Code to reproduce unexpected behavior
import java.util.Arrays;
public class HashcodeTest {
/**
* A simple Record with an int array.
*/
record Record(int[] array) {}
/**
* {@code Record#hashCode()} invokes not {@link Arrays#hashCode(int[])} but {@code int[].hashCode()}.
*/
private static void testHashCode() {
int[] array = new int[]{ 1, 2, 3 };
System.out.printf("Record#hashCode: %d%n", new Record(array).hashCode());
System.out.printf("int[].hashCode: %d%n", array.hashCode());
System.out.printf("Arrays.hashCode: %d%n", Arrays.hashCode(array));
array[0] = 0;
System.out.println("== after int array change ==");
System.out.printf("Record#hashCode: %d%n", new Record(array).hashCode());
System.out.printf("int[].hashCode: %d%n", array.hashCode());
System.out.printf("Arrays.hashCode: %d%n", Arrays.hashCode(array));
}
/**
* If each record instance has an empty array, the result of {@code Record#equals()} is expected to be {@code true}.
* But actually prints {@code false} because {@code Record#equals()} invokes not {@link Arrays#equals(int[], int[])} but {@code int[].equals(Object)}..
*/
private static void testEquals() {
System.out.println(new Record(new int[0]).equals(new Record(new int[0])));
}
public static void main(String[] args) {
testHashCode();
testEquals();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment