菜鸟译文(三)——JDK6和JDK7中substring()方法的对比
substring(int beginIndex, int endIndex)方法在JDK6和JDK7中是不同的。了解他们的区别可以让我们更好的使用这个方法。方便起见,以下用substring() 代替 substring(int beginIndex, int endIndex)。
1. substring()做了什么?
substring(int beginIndex, int endIndex)方法返回一个以beginIndex开头,以endIndex-1结尾的String对象。
String x ="abcdef"; x =x.substring(1,3); System.out.println(x);
输出:
bc
2.当substring()被调用的时候发生了什么?
也许你觉得,因为x是不可变的,当x经过substring(1,3)处理以后,会指向如下一个全新的String对象:
然而,这张图没有正确的表示出堆内存里真正发生了什么。那么当调用substring()方法时,JDK6和JDK7究竟有什么不同呢。
3. JDK 6中的substring()
String是由一个字符数组实现的,在JDK6中,String类由三部分组成:charvalue[], int offset, int count.。他们才是真正用来存储字符的数组,数组的第一个元素用来存储字符的长度。
当调用substring()方法时,会创建一个新的String对象,但是这个String对象的值仍然指向堆内存中相同的数组。真正不同的是它们的计数和偏移量。
下面的代码已经做了简化,只包含解释这一问题的关键部分。
//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); }
4.JDK 6中的substring()存在的一个问题
如果有一个非常长的String对象,但是你每次通过substring()只用到其中一小部分。这样就会有一个性能上的问题,对于JDK6来说,使用以下代码可以解决这个问题,这样做会创建一个真正的子字符串对象:
x = x.substring(x, y) + ""
5. JDK 7中的substring()
在JDK7中,substring()方法实际上会在堆内存中创建一个新的数组,这是JDK7中的一项改进。
//JDK 7 public String(char value[], int offset, int count) { //check boundary this.value = Arrays.copyOfRange(value, offset, offset + count); } public String substring(int beginIndex, int endIndex) { //check boundary int subLen = endIndex - beginIndex; return new String(value, beginIndex, subLen); }
原文地址:
http://www.programcreek.com/2013/09/the-substring-method-in-jdk-6-and-jdk-7/
最新文章
- 备份MySQL数据库
- shell脚本连接、读写、操作mysql数据库实例
- Gvr SDK for Unity 分析(一)
- WPF使用扩展屏幕
- php分享三十四:待排查问题
- CSS权威指南 - 层叠
- 【BZOJ 2243】染色 - 树链剖分+线段树
- EventBus vs Otto vs LiteEventBus
- 关于java设计模式与极品飞车游戏的思考
- SOA,ESB 与 SCA
- 【POJ3237】【树链剖分】Tree
- java aes encrypt
- python 之走坑的道路
- MQ(消息队列)常见的应用场景解析
- php判断是不是手机端访问
- 使用php的curl爬去青果教务系统 课表(转)
- git pull更新错误解决办法
- Python自动化测试用例设计--自动化测试用例与手工测试用例区别与联系
- 定时调度任务quartz
- 封装MemoryCache
热门文章
- Cocos2d-x v3.6制作射箭游戏(二)
- 人脸识别经典算法二:LBP方法
- 更改vsts源代码绑定服务器地址方法
- 需要弥补的那部分SQL
- django rest_framework--入门教程3
- Windows 8.1 应用开发后台任务概述(Windows XAML)
- [ACM_水题] ZOJ 3714 [Java Beans 环中连续m个数最大值]
- Linux:文件权限
- 最新 Windows 10 应用项目模板发布
- hasOwnProperty()&;&;isPrototypeOf()