Java Integer hashCode()方法

来源:这里教程网 时间:2026-02-17 20:51:11 作者:

Java Integer hashCode()方法

Java中Integer类的java.lang.Integer.hashCode()方法用于返回一个特定Integer的哈希代码。

语法。

public int hashCode()

参数:该方法不接受任何参数。

返回值。该方法为该对象返回一个哈希代码整数值,该值等于该Integer对象所代表的非简单的原始整数值。

下面的程序说明了Integer类的hashCode()的使用:

程序1: 当传递整数数据类型时。

// Java program to demonstrate working// of Java.lang.Integer.hashCode() Methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {        // Object s_int created        Integer s_int = new Integer("223");          // Returning a hash code value for this object         int hashcodevalue = s_int.hashCode();        System.out.println("Hash code Value for object = " + hashcodevalue);    }}

输出。

Hash code Value for object = 223

程序2: 当字符串数据类型被传递时。

注意: 这将导致NumberFormatException等运行时错误。

// Java program to demonstrate working// of Java.lang.Integer.hashCode() Methodimport java.lang.*;  public class Geeks {      public static void main(String[] args)    {        // object s_int created        Integer s_int = new Integer("gfg");          // Returning a hash code value for this object.        int hashcodevalue = s_int.hashCode();        System.out.println("Hash code Value for object = " + hashcodevalue);    }}

输出。

Exception in thread "main" java.lang.NumberFormatException: For input string: "gfg"    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)    at java.lang.Integer.parseInt(Integer.java:580)    at java.lang.Integer.(Integer.java:867)    at Geeks.main(Geeks.java:9)

相关推荐