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
- subString()源码分析
- 源码分析
- 源码分析
- 源码分析
- 源码分析
- 源码分析
- 源码分析
- 源码分析
- 源码分析
- "A".substring(1)不报异常的分析
- substr、substring、slice的比较分析
- substr、substring和slice用法分析
- [LeetCode] Longest Palindrome Substring 详细分析
- Leetcode:Longest Palindromic Substring之详细分析
- leetcode:Minimum Window Substring 细致分析
- [LeetCode] 4. Longest Palindrome Substring 分析+代码
- Longest Palindromic Substring(算法分析week3)
- (算法分析Week6)Longest Palindromic Substring[Medium]
- OJ_1124
- ocx-win7x64-ie
- HBase client api例子集合-1
- 浅谈windows句柄表
- ios开发第三方库介绍大全(收集中)
- subString()源码分析
- boost教程
- Viewpager滑动后消失
- 亲身经历故障--如何解决
- 《算法谜题》
- ios开发点滴-rejected for using the Ad support framework错误
- 设计模式之单例模式
- OJ_1125
- c语言结构体用法