1.String 为什么要设计成不可变的?
本文参考jdk1.6
The String class represents character strings. All string literals in Java programs, such as "abc", are implemented as instances of this class.
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.
string class对象代表字符串,所有的文字在程序中都是作为类的实例存在的。string是常量,初始化后不能修改,stringBuffer支持修改,string不可改变所以支持共享。
public final class String
implements java.io.Serializable, Comparable<String>, CharSequence,
Constable, ConstantDesc {
//The value is used for character storage.
//方便对象的序列号
private final byte[] value;
private final byte coder;
//hashcode 运算得到hashcode
private int hash; // Default to 0
}
final 修饰value引用不可改变
Serializable 支持序列化
Comparable 可比较的
CharSequence字符序列接口
Constable 表示常量类型
总结:string是不可变得,因此可能被共享,而且在开发中使用频繁,所以能保证线程的安全。在内存方面,string的内容是放到堆内存的常量池中,即便创建多个相同内容的对象,都指向同一个常量池内的内容。提高效率。
2.new String(“hello”) 产生几个对象
1.如果常量池内没有hello,会产生两个对象,一个是堆内string对象,一个常量池的对象。
2.如果常量池有hello内容,只会创建一个string对象就可以了