1. 媒介
最近看到几个有趣的关于Java焦点类String的问题。
翻阅了网上的一些博客和stackoverflow,团结本身的领略做一个汇总。
2. String类是如何实现不行变的
String类的一大特点,就是利用Final类修饰符。
A class can be declared final if its definition is complete and no subclasses are desired or required.
Because a final class never has any subclasses, the methods of a final class are never overridden .
Java SE 7 官方手册中的界说如上,假如你认为这个类已经界说完全而且不需要任何子类的话,可以将这个类声明为Final,Final类中的要领将永远不会被重写。
在Java中,String是被设计成一个不行变(immutable)类,一旦建设完后,字符串自己是无法通过正常手段被修改的。
private final char value[]; // 一旦初始化后,引用不能被修改 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); }
选了substring要领来做一个代表,其他常见的涉及String操纵的要领都是雷同,假如你操纵后的内容会和今朝String中的内容纷歧致的话,那么都是从头建设一个新的String类返还,不会让你去修改内部的内容。
将String类设计成Final类,可以或许制止其要领被子类重写,从而粉碎了它自己要领的实现,进而粉碎了不行变的特性。
2.1 String类设计成不行变的长处
我们都不是Java语言的设计者,不知道其为何须然要设计成不行变,试着做一些意料。
这是团结小我私家领略和stackoverflow上看的汇总,我们来看看Java语言的爸爸James Gosling是怎么说的。
From a strategic point of view, they tend to more often be trouble free. And there are usually things you can do with immutables that you can’t do with mutable things, such as cache the result. If you pass a string to a file open method, or if you pass a string to a constructor for a label in a user interface, in some APIs (like in lots of the Windows APIs) you pass in an array of characters. The receiver of that object really has to copy it, because they don’t know anything about the storage lifetime of it. And they don’t know what’s happening to the object, whether it is being changed under their feet.
You end up getting almost forced to replicate the object because you don’t know whether or not you get to own it. And one of the nice things about immutable objects is that the answer is, “Yeah, of course you do.” Because the question of ownership, who has the right to change it, doesn’t exist.
One of the things that forced Strings to be immutable was security. You have a file open method. You pass a String to it. And then it’s doing all kind of authentication checks before it gets around to doing the OS call. If you manage to do something that effectively mutated the String, after the security check and before the OS call, then boom, you’re in. But Strings are immutable, so that kind of attack doesn’t work. That precise example is what really demanded that Strings be immutable.
这是James Gosling在2001年5月的一次访谈中,谈到了不行变类和String,大意就是 他会更倾向于利用不行变类,它可以或许缓存功效,当你在传参的时候,利用不行变类不需要去思量谁大概会修改其内部的值,这个问题不存在的。假如利用可变类的话,大概需要每次记得从头拷贝出内里的值,机能会有必然的损失。
老爷子还说了,迫使String类设计成不行变的另一个原因是安详,当你在挪用其他要领,好比挪用一些系统级操纵之前,大概会有一系列校验,假如是可变类的话,大概在你校验事后,其内部的值被改变了,大概引起严重的系统瓦解问题,劳务派遣管理系统,这是迫使String类设计成不行变类的重要原因。
2.2 String Pool