import java.lang.ref.WeakReference;
/**
* Class to research strings.
* constant string like "AAA " won 't be reclaimed while instance created by new will.
*/
public class StringResearch {
public static void main(String[] args) {
String a = "AAA ";
String b = new String( "AAA ");
WeakReference wra = new WeakReference(a);
WeakReference wrb = new WeakReference(b);
a = null;
b = null;
System.gc();
System.out.println(wra.get());
System.out.println(wrb.get());
}
}
程序输出如下
AAA
null
根据以上结果,请说明通常情况下如何定义新的String变量比较好,并说明理由。
------解决方案--------------------
我记得应该是String a = "AAA "; 这个方法比较好,两个对象a, "AAA "。
String b = new String( "AAA "); 据说是多创建一个对象,3个对象a, "AAA "和引用 "AAA "的对象。
------解决方案--------------------
1楼正解
------解决方案--------------------
String a = "AAA ";
String b = new String( "AAA ");
一般前面的好
a是一个引用
b是个内存空间