Java 教程

Java hashCode() 方法

Java String类Java String类


hashCode() 方法用于返回字符串的哈希码。

字符串对象的哈希码根据以下公式计算:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]

使用 int 算法,这里 s[i] 是字符串的第 i 个字符,n 是字符串的长度,^ 表示求幂。空字符串的哈希值为 0。

语法

public int hashCode()

参数

  • 无。

返回值

返回对象的哈希码值。

实例

package com.yiibai;

import java.lang.*;

public class StringDemo {

  public static void main(String[] args) {
  
    Integer i = new Integer(50);
    Long l = new Long(50);
    Float f = new Float(50);
    Integer i2 = new Integer(0);
    
    // hash codes of different objects with same value are always same
    System.out.println("Hash code of " + i + " is =  " + i.hashCode());
    System.out.println("Hash code of " + l + " is =  " + l.hashCode());
  
    // hash code for float value i.e different from Integer and Long
    System.out.println("Hash code of " + f + " is =  " + f.hashCode());    
        
    // hash code value of number zero(0) is zero(0)
    System.out.println("Hash code of " + i2 + " is = " + i2.hashCode());

    String str = "this is yiibai";
    
    // hash code of string str
    System.out.println("Hash code of string is = " + str.hashCode());
  }
}

以上程序执行结果为:

Hash code of 50 is = 50
Hash code of 50 is = 50
Hash code of 50.0 is = 1112014848
Hash code of 0 is = 0
Hash code of string is = -1124820283

Java String类Java String类