java字符串subString的实现
2016-05-04 18:48
676 查看
1 功能: substring (beginIndex,endIndex),取字符串beginIndex和endIndex之间的字符,缺少第二个参数时,取beginIndex到字符串末尾的字符。
2 实现方法在String 类里
那么new String(value, beginIndex, subLen) 是怎么实现的呢?
追踪发现,是本地方法,调用的是c++实现的底层函数
有意思的就要来了,c++代码:else代码意义:防止新的内容覆盖掉原来的内容
2 实现方法在String 类里
public String substring(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new StringIndexOutOfBoundsException(beginIndex); } if (endIndex > value.length) { throw new StringIndexOutOfBoundsException(endIndex); } int subLen = endIndex - beginIndex; if (subLen < 0) { throw new StringIndexOutOfBoundsException(subLen); } return ((beginIndex == 0) && (endIndex == value.length)) ? this :<span style="color:#009900;"> new String(value, beginIndex, subLen)</span>; }
那么new String(value, beginIndex, subLen) 是怎么实现的呢?
public String(char value[], int offset, int count) { if (offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if (count < 0) { throw new StringIndexOutOfBoundsException(count); } // Note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } this.value = <span style="color:#009900;">Arrays.copyOfRange(value, offset, offset+count);</span> }
public static char[] copyOfRange(char[] original, int from, int to) { int newLength = to - from; if (newLength < 0) throw new IllegalArgumentException(from + " > " + to); char[] copy = new char[newLength]; <span style="color:#009900;"> System.arraycopy</span>(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; }
追踪发现,是本地方法,调用的是c++实现的底层函数
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
有意思的就要来了,c++代码:else代码意义:防止新的内容覆盖掉原来的内容
static void pd_conjoint_oops_atomic(oop* from, oop* to, size_t count) { // Do better than this: inline memmove body NEEDS CLEANUP if (from > to) { while (count-- > 0) { // Copy forwards *to++ = *from++; } } else { <span style="color:#009900;">from += count - 1; to += count - 1; while (count-- > 0) { // Copy backwards *to-- = *from--;</span> } } }
相关文章推荐
- Spring @PostConstruct and @PreDestroy example
- JAVA中正则表达式总结
- 《java入门第一季》之面向对象(成员方法)
- 《java入门第一季》之面向对象(成员方法)
- 5、Java的多态
- java 线程池的使用
- JAVA学习笔记-JAVA程序的基本结构
- Spring Security 4.X 零配置,草稿记录
- 使用@ResponseBody时候spring mvc的配置
- struts json 类型异常返回到js弹框
- java反射机制
- Java 8 新特性:扩展注解(类型注解和重复注解)
- java base64 转码和解码
- jdk动态代理最详细讲解---学习笔记
- spring aop advice
- Spring 基础特性
- json、javaBean、xml互转的几种工具介绍
- java项目开发如何自制java打补丁工具
- java项目开发如何自制java打补丁工具
- Java 全角字符转半角字符