- String是 Java 中一个比较基础的类,每个开发人员都会经常接触到。
-
substring(int beginIndex, int endIndex)
方法在不同版本的 JDK 中的实现时不同的。
substring()的作用
substring(int beginIndex, int endIndex)
方法截取字符串并返回其[beginIndex,endIndex-1]范围内容
String x = "0123456";
x = x.substring(1,3);
System.out.println(x);
输出内容:
12
调用 substring()发生了什么?
因为 String 类型是不可变的,当使用x.substring(1,3)
对 x 赋值的时候,它会指向一个全新的字符串。
JDK 6 中的 substring()
String 是通过字符数组实现的。在 jdk6 中,String 类包含三个成员变量:char value[]
, int offset
, int count
。他们分别用来存储真正的字符数组,数组的第一个位置索引以及字符串中包含的字符个数。
当调用 substring()
方法时,会创建一个新的 string 对象,但是这个 string 对象仍然指向堆中的一个字符数组。这两个对象中只有 count 和 offset 的值是不同的。
下面是 JDK6 中的源码:
//JDK 6
String(int offset, int count, char value[]) {
this.value = value;
this.offset = offset;
this.count = count;
}
public String substring(int beginIndex, int endIndex){
//check boundary
return new String(offset + beginIndex, endIndex - beginIndex, value);
}
JDK 7 中的 substring()
下面是 JDK7 中的源码:
//JDK 7
public String(char value[], int offset, int count) {
//check boundary
this.value = Array.copyOfRange(value, offset, offset + count);
}
public String substring(int beginIndex, int endIndex) {
int subLen = endIndex - beginIndex;
return new String(value, beginIndex, subLen);
}
JDK 6中 substring 导致的问题和解决
如果有一段很长的字符串,但是当你使用 substring 进行切割的时候你只需要很短的一段。这可能导致性能问题,因为需要的只是一小段字符序列,但是却引用了整个字符串(这个非常长的字符数组一直在被引用,所以无法被回收,就可能导致内存泄露)。在 JDK6中,一般采用一下方式来解决该问题,原理其实就是生成一个新的字符串并引用他。
x = x.substring(1,3) + "";
内存泄露:在计算机科学中,内存泄露指由于疏忽或错误误造成程序未能释放已经不再使用的内存。内存泄露并非指内存在物理上的消失,而是应用程序分配某段内存后,由于设计错误,导致在释放该段内存之前就事务了对该段内存的控制,从而造成了内存的浪费。