當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Java Java.lang.String.hashCode()用法及代碼示例


描述

這個java.lang.String.hashCode() 方法返回此字符串的哈希碼。 String 對象的哈希碼計算如下:

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]其中,s[i] 是字符串的第 i 個字符,n 是字符串的長度,^ 表示求冪

聲明

以下是聲明java.lang.String.hashCode()方法

public int hashCode()

參數

NA

返回值

此方法返回此對象的哈希碼值。

異常

NA

示例

下麵的例子展示了 java.lang.String.hashCode() 方法的用法。

package com.tutorialspoint;

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 tutorialspoint";
    
      // 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 = 643938959

相關用法


注:本文由純淨天空篩選整理自 Java.lang.String.hashCode() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。