Java Integer Hashcode Method

JavaJavaBeginner
Practice Now

Introduction

This lab will cover the usage of the hashCode(int n) method of the Java Integer class. We will learn how to generate a unique integer value, which is known as a hash code, for a given integer value.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL java(("`Java`")) -.-> java/ProgrammingTechniquesGroup(["`Programming Techniques`"]) java(("`Java`")) -.-> java/ObjectOrientedandAdvancedConceptsGroup(["`Object-Oriented and Advanced Concepts`"]) java(("`Java`")) -.-> java/BasicSyntaxGroup(["`Basic Syntax`"]) java(("`Java`")) -.-> java/DataStructuresGroup(["`Data Structures`"]) java(("`Java`")) -.-> java/StringManipulationGroup(["`String Manipulation`"]) java(("`Java`")) -.-> java/SystemandDataProcessingGroup(["`System and Data Processing`"]) java/ProgrammingTechniquesGroup -.-> java/scope("`Scope`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/classes_objects("`Classes/Objects`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/class_methods("`Class Methods`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/modifiers("`Modifiers`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/oop("`OOP`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/packages_api("`Packages / API`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/user_input("`User Input`") java/ObjectOrientedandAdvancedConceptsGroup -.-> java/wrapper_classes("`Wrapper Classes`") java/BasicSyntaxGroup -.-> java/identifier("`Identifier`") java/DataStructuresGroup -.-> java/arrays("`Arrays`") java/BasicSyntaxGroup -.-> java/data_types("`Data Types`") java/BasicSyntaxGroup -.-> java/for_loop("`For Loop`") java/BasicSyntaxGroup -.-> java/operators("`Operators`") java/BasicSyntaxGroup -.-> java/output("`Output`") java/StringManipulationGroup -.-> java/strings("`Strings`") java/BasicSyntaxGroup -.-> java/variables("`Variables`") java/DataStructuresGroup -.-> java/arrays_methods("`Arrays Methods`") java/SystemandDataProcessingGroup -.-> java/object_methods("`Object Methods`") java/SystemandDataProcessingGroup -.-> java/system_methods("`System Methods`") subgraph Lab Skills java/scope -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/classes_objects -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/class_methods -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/modifiers -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/oop -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/packages_api -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/user_input -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/wrapper_classes -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/identifier -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/arrays -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/data_types -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/for_loop -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/operators -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/output -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/strings -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/variables -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/arrays_methods -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/object_methods -.-> lab-117714{{"`Java Integer Hashcode Method`"}} java/system_methods -.-> lab-117714{{"`Java Integer Hashcode Method`"}} end

Creating a Java program file

Create a file named IntegerHashcode.java in the ~/project directory and open it in your favorite text editor.

touch ~/project/IntegerHashcode.java
touch ~/project/IntegerHashcode.java

Importing the required class

Import the Integer class from the java.lang package.

import java.lang.Integer;

Generating hash codes for integer values

In this step, we will generate hash codes for integer values using the hashCode(int n) method. We will create an application that prompts the user to enter an integer value and then generates the hash code value for the entered integer.

import java.lang.Integer;
import java.util.Scanner;

public class IntegerHashcode {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter an integer value: ");
        int value = sc.nextInt();

        int hashValue = Integer.hashCode(value);

        System.out.println("Hash code value for " + value + " is " + hashValue);
    }
}

In the above code, we have imported the Scanner class from the java.util package for input. We prompt the user to enter an integer value and read it using the nextInt() method of the Scanner class. We then generate the hash code value for the entered integer using the hashCode(int n) method and print it on the console using the println() method.

Compiling and running the program

Save and close the file. Compile the IntegerHashcode.java file using the below command.

javac IntegerHashcode.java

Run the program using the below command.

java IntegerHashcode

You will be prompted to enter an integer value. Enter any integer value and press the enter key. The program will generate the hash code value for the entered integer value and display it on the console.

Modifying the program

Let's modify the application to generate hash codes for multiple integer values entered by the user.

import java.lang.Integer;
import java.util.Arrays;
import java.util.Scanner;

public class IntegerHashcode {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of integer values: ");
        int count = sc.nextInt();
        int[] values = new int[count];

        for (int i = 0; i < count; i++) {
            System.out.print("Enter integer value " + (i+1) + ": ");
            values[i] = sc.nextInt();
        }

        int[] hashValues = new int[count];

        for (int i = 0; i < count; i++) {
            hashValues[i] = Integer.hashCode(values[i]);
        }

        System.out.println("Entered integer values: " + Arrays.toString(values));
        System.out.println("Corresponding hash code values: " + Arrays.toString(hashValues));
    }
}

In the above code, we have added a loop to read multiple integer values from the user and generate hash code values for them. We store the integer values and hash code values in separate arrays and print them on the console using the toString() method of the Arrays class.

Compiling and running the modified program

Save and close the file. Compile the IntegerHashcode.java file again using the below command.

javac IntegerHashcode.java

Run the modified program using the below command.

java IntegerHashcode

Follow the prompts to enter multiple integer values. The program will generate hash code values for each integer value and display them on the console.

Exploring hash code collisions

A hash code collision occurs when multiple objects generate the same hash code value. Although the hashCode(int n) method generates unique hash code values for any given integer value, it is not foolproof. There is still a possibility of hash code collisions, especially when the hash code values and the underlying algorithm generating the hash codes are not strong enough.

Let's demonstrate a hash code collision using the hashCode(int n) method. Modify the application by generating hash code values for a set of predefined integer values as shown below.

import java.lang.Integer;
import java.util.Arrays;

public class IntegerHashcode {
    public static void main(String[] args) {
        int[] values = {100, 200, 300, 400, 500};

        int[] hashValues = new int[values.length];

        for (int i = 0; i < values.length; i++) {
            hashValues[i] = Integer.hashCode(values[i]);
        }

        System.out.println("Input integer values: " + Arrays.toString(values));
        System.out.println("Corresponding hash code values: " + Arrays.toString(hashValues));
    }
}

In the above code, we have predefined an array of integer values and generate hash code values for each of them. We then print both the input values and their corresponding hash code values on the console.

Compiling and running the final program

Save and close the file. Compile the IntegerHashcode.java file one final time using the below command.

javac IntegerHashcode.java

Run the final program using the below command.

java IntegerHashcode

You will notice that the hash code values of 100 and 200 are the same. This is a hash code collision. Although hash code collisions are rare, they can potentially cause issues with hash-based collections in Java.

Summary

In this lab, we learned about the hashCode(int n) method of the Java Integer class. We learned how to generate unique hash code values for integer values using this method. We also learned how to handle hash code collisions and the limitations of hash codes in Java.

Other Java Tutorials you may like