Java Integer.hashCode(int)
方法
原文:https://www.studytonight.com/java-wrapper-class/java-integer-hashcode-int-method
hashCode(int n)
方法与 Java 1.8 或更高版本兼容,并且是java.lang
包的Integer
类的一部分。它用于返回作为参数传递的整数的哈希代码。
该方法与Integer
类的**[Integer.hashCode()](https://www.studytonight.com/java-wrapper-class/java-integer-hashcode-method)**
方法兼容。
语法:
public static int hashCode(int value)
参数:
参数包括要生成哈希代码的 int 值。
返回:
与作为参数传递的整数值关联的唯一整数值(哈希代码)。
例外情况:
在执行此方法的过程中,可能会遇到以下异常:
InputMismatchException
NumberFormatException
例 1:
这里,使用hashCode(int n)
函数,传递的整数值被转换成其各自的 hashcode。
import java.lang.Integer;
public class StudyTonight
{
public static void main(String[] args)
{
int hv1 = Integer.hashCode(27); //generate the hashcode of the passed argument
int hv2 = Integer.hashCode(81);
System.out.println("Hash code Value is: " + hv1);
System.out.println("Hash code Value is: " + hv2);
}
}
哈希码值为:27 哈希码值为:81
例 2:
这里有一个用户定义的例子,任何使用这个代码的人都可以输入自己选择的值,并获得等效的哈希代码。
import java.util.Scanner;
public class StudyTonight
{
public static void main(String[] args)
{
try
{
System.out.print("Enter the value: ");
Scanner sc = new Scanner(System.in);
Integer i = sc.nextInt();
int hv = Integer.hashCode(i); // Returning hash code value for this object
System.out.println("Hash code is: " + hv);
}
catch(Exception e)
{
System.out.println("Invalid Input!!");
}
}
}
输入值:545 哈希码为:545 *输入值:莫希特 无效输入!!
实时示例:
在这里,您可以测试实时代码示例。您可以为不同的值执行示例,甚至可以编辑和编写您的示例来测试 Java 代码。