Java - Short hashCode() 方法



Java Short hashCode() 方法检索给定 Short 对象的哈希码。Java 中的每个对象都有一个关联的哈希码,它是一个唯一的原始整数值。此方法检索的值与 intValue() 方法返回的值相同。

使用计算机科学中基本的哈希概念,对象或实体被映射到整数值。这些值被称为实体的哈希值或哈希码。

此方法有两个多态变体。下面将讨论这些变体的语法。

语法

以下是Java Short hashCode() 方法的语法:

public int hashCode() or, public static int hashCode(short x)

参数

  • x − 它是哈希值

Learn Java in-depth with real-world projects through our Java certification course. Enroll and become a certified expert to boost your career.

返回值

给定 Short 对象的哈希码

获取具有正值的 Short 对象的哈希码示例

以下示例显示了 Java Short hashCode() 方法的用法。这里我们创建一个具有正值的 Short 对象。然后使用此方法打印哈希码:

Open Compiler
package com.tutorialspoint; public class ShortDemo { public static void main(String[] args) { short value1 = 8487; Short value2 = new Short(value1); // The hash code method int value3 = value2.hashCode(); System.out.println("The Hash code value is = " + value3); // The hash code static method Short value4 = new Short("8487"); System.out.println("The short value is = " + Short.hashCode(value4)); } }

输出

让我们编译并运行上面的程序,这将产生以下结果:

The Hash code value is = 8487
The short value is  = 8487

获取具有正值的 Short 对象的哈希码示例

以下是 hashCode() 方法的另一个示例:

Open Compiler
package com.tutorialspoint; public class ShortDemo { public static void main(String[] args) { // create the Short objects Short value1 = 87; Short value2 = 987; // print the hashcode of the Short objects System.out.println("hashCode of value1 is: " + value1.hashCode()); System.out.println("hashCode of value2 is: " + value2.hashCode()); } }

输出

以下是上述代码的输出:

hashCode of value1 is: 87
hashCode of value2 is: 987

获取具有负值的 Short 对象的哈希码示例

在下面的示例中,我们尝试查找负值的哈希码:

Open Compiler
package com.tutorialspoint; public class ShortDemo { public static void main(String[] args) { // passing the negative integer Short value1 = new Short("-36"); System.out.println("Hash Value of negative integer is = " + value1.hashCode()); } }

输出

执行上述程序后,获得的输出如下:

Hash Value of negative integer is = -36

获取 Short 对象的哈希码示例

在下面的代码中,将负值和正值 short 值作为参数传递,以打印传递值的等效哈希码值:

Open Compiler
package com.tutorialspoint; public class ShortDemo { public static void main(String[] args) { short s1 = 987; short s2 = -786; // returning the hash code value int h1 = Short.hashCode(s1); int h2 = Short.hashCode(s2); System.out.println("hash code value of s1 is: " + h1); System.out.println("hash code value of s2 is: " + h2); } }

输出

执行上述代码时,我们得到以下输出:

hash code value of s1 is: 987
hash code value of s2 is: -786
java_lang_short.htm
广告