起初,写代码时遇到了一些不懂的问题,于是百度搜索相关的信息。可是让我很失望,有些网站提出的解决方法,一开题就罗里吧嗦,一直到网页尾部,我都没看明白他到底要叙述什么。还有些网站给出的方案,我一眼就看出来根本不对。于是,就开始了源代码的研究。
就像字符串的substring(int beginIndex, int endIndex) 方法,很多人都会调用这个api,可是真的知道它的底层是怎么实现的吗?而且,你知道java.lang.String类有个char[] value 属性吗?我接下来给出这个方法底层实现。
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 : new String(value, beginIndex, subLen); }
加粗部分又调用了一个String的构造器,我们再来看。
public String(char[] value, int offset, int count) { if(offset < 0) { throw new StringIndexOutOfBoundsException(offset); } if(count <= 0) { if(count < 0) { throw new StringIndexOutOfBoundsException(count); } if(offset == 0) { this.value = "".value; return ; } } if(offset + count > value.length) { throw new StringIndexOutOfBoundsException(offset + count); } this.value = Arrays.copyOfRange(value, offset, offset + count); }
从这段代码中,可以分析得到substring() 的api 核心代码其实就是 Arrays.copyOfRange(value, offset, offset + count)
看到了底层代码,我们以后使用这个api会更加有底气了吧。
底层代码的研究固然繁琐,需要的时间会长一些,但是我们从中获得的知识, 其实远远大于只会调用api的经验。