subString()源码分析

来源:互联网 发布:sketchup mac版界面 编辑:程序博客网 时间:2024/06/01 09:58

截取子字符串是字符串最常用的操作之一。Java的String类提供了两个截取子字符串的方法:

public String substring(int beginIndex);

public String substring(int beginIndex, int endIndex) ;
在JDK1.6,这两者的源代码如下:

public String substring(int beginIndex) {return substring(beginIndex, count);    }

public String substring(int beginIndex, int endIndex) {if (beginIndex < 0) {throw new StringIndexOutOfBoundsException(beginIndex);}if (endIndex > count) { throw new StringIndexOutOfBoundsException(endIndex);}if (beginIndex > endIndex) { throw new StringIndexOutOfBoundsException(endIndex - beginIndex);}return ((beginIndex == 0) && (endIndex == count)) ? this :    new String(offset + beginIndex, endIndex - beginIndex, value);}


substring(int beginIndex, int endIndex)源码为例,我们可以看出,在方法的最后,返回了一个新建的String对象。

String的构造函数如下:

 String(int offset, int count, char value[]) {this.value = value;this.offset = offset;this.count = count;    }

其中,offset代表偏移量,count代表字符串长度,char value[]是生成字符串的字符数组。

注:这是一个包内私有构造函数,应用程序无法使用它。subString()方法的内存泄露也是因为它。


当我们使用substring()方法时,原String的内容将value数组将被复制到子字符串中,然后子字符串根据偏移量和长度来决定自己的实际取值。

这种方法提高了运算速度,却浪费了大量内存空间。

0 0
原创粉丝点击