-4

今日、私は以下のコードを試していましたが、両方の sysout で出力が異なることを期待していました。

public class StringDemo {


    public static void main(String[] args) {
        String s1 = new String("Hi");
        String s2 = new String("Hi");       
        System.out.println(s1.hashCode());
        System.out.println(s2.hashCode());
    }

}

しかし、私は同じ値を取得しています。誰かが私に物事がどのように機能しているのか説明してもらえますか?

ありがとう、ソウラフ

4

5 に答える 5

5

StringhashCode()の内容に基づいた (ありがたいことに)の独自の実装がありStringます。そうは言っても、(作成方法に関係なく) 2 つの等しい文字列がある場合、最終的には同じhashCode().

JDK 7 からの実装をString.hashCode()次に示します(簡略化)。

public int hashCode() {
    int off = offset;
    char val[] = value;
    int len = count;

     for (int i = 0; i < len; i++) {
         h = 31*h + val[off++];
    }
    return h;
}

ご覧のとおり、の内容のみに基づいていStringます。

于 2013-01-10T12:33:17.857 に答える
1

StringのhashCode()仕様は JLS によって規定されており、String の文字に完全に基づいています。これは、Java のすべてのバージョンとすべての JVM の開始に対して予測可能で一貫性があります。

于 2013-01-10T12:34:32.137 に答える
1

http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#hashCode%28%29から

public int hashCode()

    Returns a hash code for this string. The hash code for a String object is computed as

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


    using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

    Overrides:
        hashCode in class Object

    Returns:
        a hash code value for this object.
于 2013-01-10T12:35:20.777 に答える
0

String は、同じ文字列に対して同じ hashCode を返す方法で hashCode を実装しています。これは、hashCode が実装されていないオブジェクトでは異なることに注意してください。通常、hashCode に対して異なる値を返します。

于 2013-01-10T12:33:13.650 に答える
0

String のソース コードから、

String オブジェクトのハッシュ コードは次のように計算されます。

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

int 演算を使用します。ここで、s[i] は文字列の i 番目の文字、n は文字列の長さ、^ はべき乗を示します。(空の文字列のハッシュ値はゼロです。)

于 2013-01-10T12:36:43.867 に答える