说明:
继承自Object,实现了java.io.Serializable、Comparable、CharSequence接口
String类代表字符串,字符串是常量,他们的值创建之后不能更改。字符串缓冲区支持可变的字符串;因为String对象是不可变的,所以可以共享
除非另行说明,否则将 null 参数传递给此类中的构造方法或方法将抛出 NullPointerException。
构造函数:
1.String() -创建一个空字符串序列
public String() { this.value = "".value; }
2.String(String original)-创建传入参数的字符串的副本
public String(String original) {
this.value = original.value;
this.hash = original.hash;
}
3.String(char[] value) -传入char数组,生成String对象
public String(char value[]) {
this.value = Arrays.copyOf(value, value.length);
}
4.String(char value[], int offset, int count) --传入char数组,从第offset起开始截取,截取长度为count
public String(char value[], int offset, int count) {
if (offset < 0) {
throw new StringIndexOutOfBoundsException(offset);
}
//如果初始偏移量即初始索引小于0时,抛出数值越界异常,index为offset
if (count <= 0) {
if (count < 0) {
throw new StringIndexOutOfBoundsException(count);
}
if (offset <= value.length) {
this.value = "".value;
return;
}
}
//若截取长度小于等于0时
//若小于零抛出数值越界异常,index为count
//若截取长度等于零时,如果offset小于等于数组长度,返回值均为空字符串
if (offset > value.length - count) {
throw new StringIndexOutOfBoundsException(offset + count);
}
//若初始偏移量+截取长度大于数组长度,抛出数值越界异常,index为ofset+count
this.value = Arrays.copyOfRange(value, offset, offset+count);
//传入char数组,从第offset起开始截取,截取长度为count
}
5.String(int[] codePoints, int offset, int count) -传入int类型代码数组,从第offset起开始截取,截取长度为count
public String(int[] codePoints, int offset, int count) {
if(offset< 0) {
thrownewStringIndexOutOfBoundsException(offset);
}
//如果初始偏移量小于0,抛出数值越界异常,index=offset
if(count<= 0) {
if(count< 0) {
thrownewStringIndexOutOfBoundsException(count);
}
if(offset<=codePoints.length) {
this.value="".value;
return;
}
}
//若截取长度小于等于0时
//若小于零抛出数值越界异常,index为count
//若截取长度等于零时,如果offset小于等于数组长度,返回值均为空字符串
// Note: offset or count might be near -1>>>1.
if (offset > codePoints.length - count) {
thrownewStringIndexOutOfBoundsException(offset+count);
}
//若初始偏移量+截取长度大于数组长度,抛出数值越界异常,index为ofset+count
final int end=offset+count;
//获取截取数组末位的索引值 offset+count
// Pass 1: Compute precise size of char[] 计算char数组的大小
int n=count;
for(int i=offset;i<end;i++){
int c=codePoints[i];
if(Character.isBmpCodePoint(c)) //判断数组中的int值是否在BMP范围内
continue; //如果是 跳出本轮循环,继续判断数组中下一个值
//如果不是,判断数组中指定的代码点是否为从 0x0000 到 0x10FFFF 范围之内的有效 Unicode 代码点值。
else if(Character.isValidCodePoint(c))
//如果是 增加n的计数,n的值=偏移量count+0x0000 到 0x10FFFF 范围之内的有效 Unicode 代码点值有效个数
n++;
//如果不是抛出异常:不合法的参数异常IllegalArgumentException
else throw newIllegalArgumentException(Integer.toString(c));
}
// Pass 2: Allocate and fill in char[] 将代码点放入char[] 数组
final char[] v = new char[n];
for(int i=offset,j= 0;i<end;i++,j++){
int c=codePoints[i];
//判断代码点是否在BMP范围内,如果是,强转成char类型
if(Character.isBmpCodePoint(c))
v[j] = (char)c;
else
Character.toSurrogates(c,v,j++);
/**
* static void toSurrogates(int codePoint, char[] dst, int index) {
dst[index+1] = lowSurrogate(codePoint);
dst[index] = highSurrogate(codePoint);
}
*/
}
this.value=v;
}
作者:nzdnllm
链接:https://www.jianshu.com/p/cc21ef7c9340
来源:简书