怎么不同?
String a = "ok"和
String a = new String("ok")
不都是生成一個字符串對象嗎?只是
String a = "ok";
String b = "ok";
a,b不同﹐它們是兩個對象﹐不過由於JVM的內存優化﹐實際上開始時兩個對象都是指向一塊內存區域﹐只是在使用時再復製出一塊新的內存來
String a = "ok"和
String a = new String("ok")
不都是生成一個字符串對象嗎?只是
String a = "ok";
String b = "ok";
a,b不同﹐它們是兩個對象﹐不過由於JVM的內存優化﹐實際上開始時兩個對象都是指向一塊內存區域﹐只是在使用時再復製出一塊新的內存來
一样吗?不一样,不信你试试:
String a="ok";
String b=new String("ok");
if(a==b)
{
out.println("ok");
}
else
{
out.println("fail");
}
或则
if(a.equals(b))
{
out.println("ok");
}
else
{
out.println("fail");
}
这是由他们不同的存储方式决定的
"Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str = new String(data);
"
不知何解
//String b=new String("ok");
String b="ok";
if(a==b)
{
out.println("ok");
}
else
{
out.println("fail");
}
中的结果是ok
这个是为什么?
"Strings are constant; their values cannot be changed after they are created. String buffers support mutable strings. Because String objects are immutable they can be shared. For example:
String str1 = "abc";
is equivalent to:
char data[] = {'a', 'b', 'c'};
String str2 = new String(data);
"
不知何解str1.equals(str2) ///println为true;
应该这样理解,不知对否
String b = new String("ok")
第一种方法中"ok"是一个字符串常量,不是在什么堆栈中,而是在一个常数池中,在执行这句的类加载的时候,就被放到这个常数池中而且保持唯一性,赋值只是把一个句柄变量指向这个常数池中的变量"ok".第二种方法源码如下
public String(String original) {
this.count = original.count;
if (original.value.length > this.count) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
this.value = new char[this.count];
System.arraycopy(original.value, original.offset,
this.value, 0, this.count);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
this.value = original.value;
}
}
可以看到,实际上是进行字符串复制,把原来在常数池中的字符串"ok"复制为一个新的对象.赋给对象对象句柄b , a!=b ,,所以这两个句柄是不相同的.
但是 b.intern()==a.intern();
b.intern()==a;