1、String源码结构
public final class String implements java.io.Serializable, Comparable<String>, CharSequence { /** The value is used for character storage. */ //用于存储字符的字符数组,值不可更改 private final char value[]; /** Cache the hash code for the string */ //该字符的hash code; 默认为0 private int hash; // Default to 0 ...... }
String类被final修饰,说明该类不能被继承。String类用字符数组存储数据,说明该数组变成了常量,只能被赋值一次。
2、String类的构造函数
我们以 String(char value[], int offset, int count)构造函数为例
//返回一个新的字符串,其中以指定位置的offset的字符开始,长度为count 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 <= value.length) { this.value = "".value; return; } } // Note: offset or count might be near -1>>>1. if (offset > value.length - count) { throw new StringIndexOutOfBoundsException(offset + count); } //把一个新指定字符数组(从offset开始,以offset+count结尾)赋值给新的字符串value属性。 this.value = Arrays.copyOfRange(value, offset, offset+count); } //Arrays.copyOfRange(value, offset, offset+count)方法 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]; System.arraycopy(original, from, copy, 0, Math.min(original.length - from, newLength)); return copy; }
System.arraycopy是一个native方法
public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length);
作者:Work Hard Work Smart
出处:http://www.cnblogs.com/linlf03/
欢迎任何形式的转载,未经作者同意,请保留此段声明!