Signup/Sign In
PUBLISHED ON: JANUARY 21, 2021

Java Arrays deepHashCode() Method

In this tutorial, we will learn about the deepHashCode() method and its implementation. This method belongs to the Arrays class which is located in java.util package. It returns a hash code based on the "deep contents" of the specified array.

Syntax

public static int deepHashCode(Object[] a)

This method will receive an array and compute hash code based on the deep content in an array and return it in an integer.

Example of deepHashCode() to Get Hash Code

In the example below, we are passing an array to the method deepHashCode() and it will return a hash based on the deep content of an array. Although it generates a hash code but doesn't guarantee that it will be unique for two different arrays.

import java.util.Arrays;
class StudyTonight { 
	public static void main(String args[]) 
	{ 
		int array[][] = { 
				{ 1, 9 }, 
				{ 13, 17 }, 
				{ 31, 18} }; 		
		System.out.println(Arrays.deepHashCode(array));
	} 
}


1036503

Example of deepHashCode() to Get Hash Code

In the example below, we can see both arrays are different but since all the elements exist in both arrays it is generating the same hash value.

So it is very clear from this example that even though there is inequality in two arrays but based on the deep content it may generate the same hash code.

import java.util.Arrays;
class StudyTonight { 
	public static void main(String args[]) 
	{ 
		int[][] array1 = {
				{ 8, 7, 4 }, 
				{ 3, 6, 5 },
				{ 0, 2, 1 } };
		int[][] array2 = {
				{ 8, 4, 0 }, 
				{ 6, 7, 5 }, 
				{ 3, 2, 1 } };
		System.out.println("Hash array1 " + Arrays.deepHashCode(array1));
		System.out.println("Hash array2 " + Arrays.deepHashCode(array2));
	} 
}


Hash array1 37308160
Hash array2 37308160

Conclusion:

In this tutorial, we learned how to use deepHashCode() to generate a hash value based on the deep content of an array. Even after having the same content just because of a different arrangement deepHashCode() method will not change the hash code and so it does not necessarily produce unique code.



About the author:
I am the founder of Studytonight. I like writing content about C/C++, DBMS, Java, Docker, general How-tos, Linux, PHP, Java, Go lang, Cloud, and Web development. I have 10 years of diverse experience in software development.