| by Arround The Web | No comments

Java hashCode()

The “hash code” in Java is utilized to streamline the hashing in hash tables. The “hashcode()” method can store the data efficiently and access them instantly simultaneously. Moreover, this method is also effective in searching for an object having a “unique” code. In such cases, this method is convenient for the programmer to cope with various situations efficiently.

This blog will elaborate on using and implementing Java’s “hashCode()” method.

What is “hashCode()” in Java?

A “hash code” is an integer value associated with each Java object and returns a “4” bytes value. The “hashCode()” method is a Java Integer class method that gives the hash code for the provided inputs.

Syntax

hashCode(val)

In this syntax, “val” determines the hash code.

Example 1: Utilization of “hashCode()” Upon the Integer Objects

In this example, two integer objects can be created, and their corresponding “hash code” can be retrieved:

Integer i = new Integer("2");

Integer j = new Integer("3");

int hashValue1 = i.hashCode();

int hashValue2 = j.hashCode();

System.out.println("Hash code Value for the first object is: " + hashValue1);

System.out.println("Hash code Value for the second object is: " + hashValue2);

Apply the following steps, as given in the above code:

  • First of all, create two “Integer” objects named “i” and “j” using the “new” keyword and the “Integer()” constructor, respectively, and allocate the specified integer values.
  • After that, associate the “hashCode()” method with each of the created objects.
  • Lastly, display the corresponding hash code against each integer object.

Output

In the above output, it can be observed that the corresponding hash codes against the integers are displayed.

Example 2: Utilization of “hashCode()” Upon the String Objects

In this specific example, the “hash code” against the “String” objects can be returned:

String i = new String("200");

String j = new String("300");

System.out.println("The hash code value of first string object is: "+i.hashCode());

System.out.println("The hash code value of second string object is: "+j.hashCode());

Apply the following steps in accordance with the above lines of code:

  • Create two “String” objects named “i” and “j” and specify the string values.
  • Now, associate the “hashCode()” method with each created object.
  • Finally, return the hash codes of the string objects.

Output

The above output indicates that the corresponding “hash code” against the string values is displayed.

Conclusion

A hash code corresponds to an integer value associated with each Java object. The “hashCode()” method in Java gives the hash code for the provided inputs. This method can be applied to fetch the hash code of the “Integer” and “String” objects. This blog compiled the approaches to utilize Java’s “hashCode()” method.

Share Button

Source: linuxhint.com

Leave a Reply