The accepted answer is correct: using Arrays.hashCode gives the same results for byte [] with the same values. Arrays.deepHashCode is necessary if you have a nested (deep) structure.
import java.util.Arrays; public class A { public static void main(String[] args) { byte[] a = {10, 32, -43, 80}; byte[] b = {13, -40}; byte[] c = {10, 32, -43, 80}; System.out.println("NOTE: A and C have identical values, B differs"); System.out.println("Using byte[].hashCode(): A and C have different hash codes"); System.out.println("a = " + a.hashCode()); System.out.println("b = " + b.hashCode()); System.out.println("c = " + c.hashCode()); System.out.println("Using Arrays.hashCode(): A and C have identical hash codes"); System.out.println("a = " + Arrays.hashCode(a)); System.out.println("b = " + Arrays.hashCode(b)); System.out.println("c = " + Arrays.hashCode(c)); System.out.println("Using Arrays.deepHashCode(): A and C have identical hash codes"); System.out.println("a = " + Arrays.deepHashCode(new Object[]{a})); System.out.println("b = " + Arrays.deepHashCode(new Object[]{b})); System.out.println("c = " + Arrays.deepHashCode(new Object[]{c})); } }
This leads to the conclusion:
NOTE: A and C have identical values, B differs Using byte[].hashCode(): A and C have different hash codes a = 141847843 b = 329849131 c = 1119051810 Using Arrays.hashCode(): A and C have identical hash codes a = 1250930 b = 1324 c = 1250930 Using Arrays.deepHashCode(): A and C have identical hash codes a = 1250961 b = 1355 c = 1250961
Here is an example of when Arrays.deepHashCode is needed
import java.util.Arrays; public class B { public static void main(String[] args) { Object[] d = {"abc", "def", new String[]{"ghi"}}; Object[] e = {"abc", "def", new String[]{"ghi"}}; System.out.println("NOTE: D and E have identical nested values"); System.out.println("Using Object[].hashCode(): different"); System.out.println("d = " + d.hashCode()); System.out.println("f = " + e.hashCode()); System.out.println("Using Arrays.hashCode(): still different"); System.out.println("d = " + Arrays.hashCode(d)); System.out.println("e = " + Arrays.hashCode(e)); System.out.println("Using Arrays.deepHashCode(): identical"); System.out.println("d = " + Arrays.deepHashCode(d)); System.out.println("e = " + Arrays.deepHashCode(e)); } }
output:
NOTE: D and E have identical nested values Using Object[].hashCode(): different d = 241990244 f = 1943487137 Using Arrays.hashCode(): still different d = 1057745997 e = 709187068 Using Arrays.deepHashCode(): identical d = 95807651 e = 95807651
source share