Java Integer hashCode() 方法

2025 年 3 月 25 日 | 阅读 3 分钟

hashCode() 方法是 Java Integer 的一个方法,它返回给定输入的哈希码。Java hashCode() 方法有两种不同的类型,可以根据其参数进行区分。

它们是

  1. Java Integer hashCode() 方法
  2. Java Integer hashCode(int value) 方法

hashCode() 方法

hashCode()Java Integer 类的一个方法,用于确定给定整数的哈希码。它覆盖了 Object 类中的 hashCode 方法。默认情况下,此方法返回一个随机整数,该整数对于每个实例都是唯一的。

hashCode(int value) 方法

hashCode(int value) 是 Java Integer 类的一个内置方法,用于确定给定 int 值的哈希码。此方法与 Integer.hashCode() 兼容。

语法

下面是 hashCode() 方法的声明

参数

数据类型参数描述
int它是一个 int 值,用于确定哈希码。

返回值

方法返回值
hashCode()它返回此对象的哈希码值,等于此 Integer 对象所表示的原始 int 值。
hashCode(int value)它返回方法参数中指定的 int 值的哈希码值。

异常

InputMismatchException, NumberFormatException

兼容版本

hashCode()Java 1.2 及以上版本
hashCode(int value)Java 1.8 及以上版本

示例 1

输出

Hash code Value for object is: 155

示例 2

输出

1.	Enter the desired input value: 4343
Hash code Value for object is: 4343

2.	Enter the desired input value: abcd
Exception in thread "main" java.util.InputMismatchException
	at java.util.Scanner.throwFor(Scanner.java:864)
	at java.util.Scanner.next(Scanner.java:1485)
	at java.util.Scanner.nextInt(Scanner.java:2117)
	at java.util.Scanner.nextInt(Scanner.java:2076)
	at  myPackage.IntegerHashCodeExample1.main(IntegerHashCodeExample1.java:11)

示例 3

输出

Exception in thread "main" java.lang.NumberFormatException: For input string: "abcd"
	at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
	at java.lang.Integer.parseInt(Integer.java:580)
	at java.lang.Integer.(Integer.java:867)
	at myPackage.IntegerHashCodeExample3.main(IntegerHashCodeExample3.java:5)

示例 4

输出

Hash code Value for object is: 155

示例 5

输出

Enter the desired input value: 4569
Hash code Value for object is: 4569