可能重复:
Java字符串和StringPool
我创建了两个字符串
String s1="MyString";
String s2=new String("MyString");
System.out.println(s1==s2);
Run Code Online (Sandbox Code Playgroud)
它打印"false".我们知道字符串池不会为同一个字符串文字创建两个对象.
那么这里发生了什么?它在字符串池中为相同的字符串文字"MyString"创建了两个不同的字符串对象(文字).
我知道 equals()方法true在这里返回.
但是当我们使用==它时应该比较两个引用,它们应该引用String常量池中的相同String对象.
为什么即使找到匹配项,它也不会引用String池中的现有String对象?
ada*_*shr 14
第一个进入池,而第二个存储在堆上.
用s2 = s2.intern();它来返回true.
当你做一个intern()对字符串时,JVM确保该字符串是存在于池中.如果它尚不存在,则在池中创建.否则,返回已存在的实例.我认为这解释了这种==行为.
String s1="MyString";
String s2=new String("MyString");
s2 = s2.intern();
System.out.println(s1==s2);
Run Code Online (Sandbox Code Playgroud)
作为参考,这里是String.intern()文档说的:
/**
* Returns a canonical representation for the string object.
* <p>
* A pool of strings, initially empty, is maintained privately by the
* class <code>String</code>.
* <p>
* When the intern method is invoked, if the pool already contains a
* string equal to this <code>String</code> object as determined by
* the {@link #equals(Object)} method, then the string from the pool is
* returned. Otherwise, this <code>String</code> object is added to the
* pool and a reference to this <code>String</code> object is returned.
* <p>
* It follows that for any two strings <code>s</code> and <code>t</code>,
* <code>s.intern() == t.intern()</code> is <code>true</code>
* if and only if <code>s.equals(t)</code> is <code>true</code>.
* <p>
* All literal strings and string-valued constant expressions are
* interned. String literals are defined in section 3.10.5 of the
* <cite>The Java™ Language Specification</cite>.
*
* @return a string that has the same contents as this string, but is
* guaranteed to be from a pool of unique strings.
*/
public native String intern();
Run Code Online (Sandbox Code Playgroud)
在String s2=new String("MyString");你正在创建一个新实例的行中String,所以它肯定不会是同一个实例s1.
如果你这样做:
System.out.println(s1=="MyString");
Run Code Online (Sandbox Code Playgroud)
你会得到的true.