なぜオブジェクトの呼び出しのtoString()はオブジェクトヘッダの出力に影響しますか?私はJOLパッケージを使用しています

dengshuo:

L'sのコードは非常に簡単です

public class L {
}

public class Synchronized1 {
    public static void main(String[] args) {
        L l=new L();
//       System.out.println(l.toString());
       System.out.println(ClassLayout.parseInstance(l).toPrintable());
    }
}

コメント解除は、再度コードを実行すると、異なる結果、または2つの完全に異なる結果をもたらすであろう。私はこの結果の原因が何であるかを知りたいですか?ちょうど())の結果に影響を与えますが、オブジェクトの他のメソッドを呼び出すことも、このようなのhashCode(その結果に影響を与えるのtoStringを呼び出していません

toString() コメントの後

マイクNakis:

あなたの空のクラスは、class Lデフォルトの使用toString()から継承されたがclass Object

デフォルトtoString()呼び出しますhashCode()

すでに見てきたように、hashCode()また、オブジェクトのヘッダに影響を及ぼしているようです。

So, in essence, the problem can be restated as "Why does calling hashCode() alter the header of my object?"

As others have already pointed in the comments, this is happening because in the particular JVM implementation that you are using, the hashCode of an object is computed the first time hashCode() is invoked, and then it is cached in the header, so that subsequent calls to hashCode() can just return the cached value, without having to re-compute it again.

Besides performance, there may be an even more important reason for doing this.

JVMあなたが計算するのハッシュコードを使用していることを、計算に関与ランダムがあるかもしれない、またはそれは、その後の試みは、オブジェクトのハッシュコードを再現することかもしれので、常にインクリメント数種があるかもしれませんが、手段を持たないだろうかに応じて、第1の演算と全く同じ値を生成します。非常に最初の計算はハッシュコード値は、後に永遠にされるか決定しなければならないことをこれが意味。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=312749&siteId=1