源码能体现语言的很多特性,对java源码进行阅读,做一下笔记,自己知识水平有限,希望大家指正。
java String 源码阅读(1)
java String类,内部有char数组实现。主要属性,value为char[]数组,可以认为是String的Model,是String类主要数据存储部分,一个String对象中的char字符全部从value中某个位置连续存储。count可看做String的长度,String对象占value中的char数量。offset String中char字符在value中的存储起始位置。
value.length 不一定等于 count。如下代码体现这点。
public String(String original) {
int size = original.count;
char[] originalValue = original.value;
char[] v;
if (originalValue.length > size) {
// The array representing the String is bigger than the new
// String itself. Perhaps this constructor is being called
// in order to trim the baggage, so make a copy of the array.
//数组复制
int off = original.offset;
v = Arrays.copyOfRange(originalValue, off, off+size);
} else {
// The array representing the String is the same
// size as the String, so no point in making a copy.
v = originalValue;
}
this.offset = 0;
this.count = size;
this.value = v;
}
String 的构造方法主要是对数组的操作,数组的复制。其中String的构造方法有ASII构造,String对象构造,Unicode构造。
关于private 私有属性,在类中访问
int size = original.count;
这也是类中访问的一种方式,类中有本类对象,此对象可以直接使用属性。