标签:
构造函数
源码
public String(char value[]) {
int size = value.length;
this.offset = 0;
this.count = size;
this.value = Arrays.copyOf(value, size);
}
这其中是用了Arrays类中copyof方法,继续看看这个方法的源码
public static char[] copyOf(char[] original, int newLength) {
char[] copy = new char[newLength];
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
Math的min方法源码
public static int min(int a, int b) {
return (a <= b) ? a : b;
}
现在从下往上面看,System.arraycopy(original, 0, copy, 0, Math.min(original.length, newLength));这段代码是copy数组,将original数组赋值给copy数组。应该对这个方法做个试验:
public static void main(String[] args) {
char[] oraginal ={‘b‘,‘c‘,‘d‘,‘e‘};
char[] copy = new char[4];
System.arraycopy(oraginal, 1, copy, 0, 3);
for(int i=0;i<copy.length;i++){
System.out.print(copy[i]+" ");
}
}
上面是测试public static native void arraycopy(Object src, int srcPos, Object dest, int destPos,int length);方法的代码
这个方法是native方法,我们并不能看到起源码。这
src是源数组,srcPos源数组开始的位置,dest目的数组,destPos目的数组的起始位置,length需要被复制的长度。
继续看这次介绍的构造函数,也就是在调用构造函数时,将传入的char[]赋值给String对象的value属性,并且改变String属性的offest和count
标签:
原文地址:http://www.cnblogs.com/fckcmlf/p/4942062.html