final的使用:
以String类为例,类和类中的所有属性都是final的
属性使用final修饰保证了该属性是只读的,不能修改类用final修饰保证了该类中的方法不能被覆盖,防止子类无意间破坏不可变性
保护性拷贝:
substring方法
public String substring(int beginIndex) {if (beginIndex < 0) {throw new StringIndexOutOfBoundsException(beginIndex);}int subLen = value.length - beginIndex;if (subLen < 0) {throw new StringIndexOutOfBoundsException(subLen);}return (beginIndex == 0) ? this : new String(value, beginIndex, subLen);}
其内部调用了string的构造方法创建了一个新字符串
public String(char value[], int offset, int count) {if (offset < 0) {throw new StringIndexOutOfBoundsException(offset);}if (count <= 0) {if (count < 0) {throw new StringIndexOutOfBoundsException(count);}if (offset <= value.length) {this.value = "".value;return;}}if (offset > value.length - count) {throw new StringIndexOutOfBoundsException(offset + count);}this.value = Arrays.copyOfRange(value, offset, offset + count);}
构造新字符串的对象时,会生成新的char[] value,对内容进行复制,这种通过创建副本对象来避免共享的手段称为【保护性拷贝】
