看String源码时,最显眼的莫过于
public final class String implements java.io.Serializable, Comparable<String>, CharSequence
那么String为什么要设计为Final类型呢?
在String类的源码中,我们可以看到这段注释
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.
翻译即为:Strings为不可变的;它的值一旦被创建就无法修改。String buffers(StringBuffer/StringBuilder)才支持可变字符串。正因为其不可变的特性,所以其可以被共享。
正如注释所言,设计为final是为了
1.方便共享数据(线程安全)
示例代码如下:
public static void main(String[] args) {
String str = "123";
Thread thread = new Thread(new StringTest(str));
thread.start();
str ="456";
}
public class StringTest implements Runnable{
private String string;
@Override
public void run() {
try {
Thread.sleep(5000L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(string);
}
StringTest(String string){
this.string = string;
}
}
想象一下如果String如果是可变的话会发生什么情况呢?
5秒之后,如果String为可变,那么输出的字符串无疑会是456。而这显然是违背了我们的本意的。
设计为final保证了在传递引用后的修改不会对之前的操作发生影响,即可方便共享数据(线程安全)。而且观察源码即可发现其中的substring()、concat()
等方法全部返回了新字符串,即不会对原有字符串产生修改。
//可以看到两个方法全部返回了新的字符串 并没有对原有对象产生修改
public String concat(String str) {
int otherLen = str.length();
if (otherLen == 0) {
return this;
}
int len = value.length;
char buf[] = Arrays.copyOf(value, len + otherLen);
str.getChars(buf, len);
return new String(buf, true);
}
public String substring(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new StringIndexOutOfBoundsException(beginIndex);
}
if (endIndex > value.length) {
throw new StringIndexOutOfBoundsException(endIndex);
}
int subLen = endIndex - beginIndex;
if (subLen < 0) {
throw new StringIndexOutOfBoundsException(subLen);
}
return ((beginIndex == 0) && (endIndex == value.length)) ? this
: new String(value, beginIndex, subLen);
}
2.保证安全性
String作为内置的数据类型之一,使用无疑是即为广泛的。
如果String不为final class,意味着其可以被继承,方法可以被重写,这无疑存在巨大的安全风险。设置为final则避免了因为继承引起的安全隐患。
其他基本数据类型包装类,比如Integer、Double、Float
等全部设置为final。
3.提高运行效率
提高运行效率个人理解可以从两个方面进行解释:
- ①因为String是final的,本身就是线程安全的,不需要进行额外的处理;
- ②字符串的分配,和其他的对象分配一样,耗费高昂的时间与空间代价,作为最基础的数据类型,大量频繁的创建字符串,肯定会极大程度地影响程序的性能。
这里不得不提到JVM的字符串常量池这一机制了。当创建一个String对象时,假如此字符串值已经存在于常量池中,则不会创建一个新的对象,而是引用已经存在的对象。因此字符串常量池的存在减少了内存开销和重复对象的创建。