Java Integer.hashCode()方法

原文:https://www.studytonight.com/java-wrapper-class/java-integer-hashcode-method

hashCode()方法是java.lang包的Integer类的一部分。它用于返回给定输入的哈希代码。hashcode 被定义为与 Java 中的每个对象相关联的唯一原始整数值。

该方法覆盖类Object.的方法

语法:

public int hashCode()

参数:

此方法中没有传递任何参数。

返回:

与整数对象关联的等效基本整数值(哈希代码)。

例外情况:

在执行此方法的过程中,可能会遇到以下异常:

  • InputMismatchException
  • NumberFormatException

例 1:

这里,使用 hashcode()函数,编译器返回一个 hashCode。

import java.lang.Integer;

public class StudyTonight
{  
    public static void main(String[] args)  
    {  

        Integer n1 = 81;
        Integer n2 = 27;

        int hv1 = n1.hashCode();//Returning the hash code value for the object n1
        int hv2 = n2.hashCode();//Returning the hash code value for the object n2
        System.out.println("Hash code Value : " + hv1);
        System.out.println("Hash code Value : " + hv2);  
    }  
}

哈希码值:81 哈希码值:27

例 2:

这里有一个用户定义的例子,任何使用这个代码的人都可以输入自己选择的值,并获得等效的哈希代码。

import java.util.Scanner;  

public class StudyTonight
{  
    public static void main(String[] args)
      {  
        try
        {
          System.out.print("Enter input: ");  
          Scanner sc = new Scanner(System.in);         
          Integer n = sc.nextInt();  
          int hv = n.hashCode(); //Returning the hash code value for the object 
          System.out.println("Hash code Value for the given input is: " + hv);

        }
        catch(Exception e)
        {
          System.out.println("Invalid Input!!");
        }

      }  
}

输入输入:23 给定输入的哈希码值为:23 *输入:今晚学习 输入无效!!

实时示例:

在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。