私はこのコードを持っています
String a="test";
String b="test";
if(a==b)
System.out.println("a == b");
else
System.out.println("Not True");
そして、すべての Java 専門家は、文字列プーリング機能if(a==b)
により、ここが通過することを知っています。
文字列プーリングによると、それが上記のコードで条件が合格した理由です。ここで質問があります。上記のコードで、2 行追加すると、文字列 a と b の値は になります。新しいコードは次のようになります
Each time your code creates a string literal, the JVM checks the string literal pool first. If the string already exists in the pool, a reference to the pooled instance is returned. If the string does not exist in the pool, a new String object is created and placed in the pool. JVM keeps at most one object of any String in this pool. String literals always refer to an object in the string pool
a+="1"
b+="1"
Test1
String a="test";
String b="test";
if(a==b)
System.out.println("a == b");
else
System.out.println("Not True");
a+="1"; //it would be test1 now
b+="1"; //it would also be test1 now
if(a==b)
System.out.println("a == b");
else
System.out.println("Not True");
文字列を変更した後、if(a==b)
チェックを入れたときに合格しませんでした.これは文字列の不変性機能によるものであることはわかっていますが、知りたい
1)変更後、JVMはそれらを2つの異なるオブジェクトで保存しますか?
2) JVM はnew String()
文字列の変更を要求しますか?
3)intern()
変更中にコールしようとしても、シングルとして参照されないのはなぜですか?
Q3 ヒント:
a+="1".intern();
b+="1".intern();