Skip to content

Instantly share code, notes, and snippets.

@KengoTODA
Created April 14, 2021 00:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KengoTODA/4d7ef6a5226d347ad9385241fee6bc63 to your computer and use it in GitHub Desktop.
Save KengoTODA/4d7ef6a5226d347ad9385241fee6bc63 to your computer and use it in GitHub Desktop.
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