Java源码___String类(二)

java.lang.String 分析摘要:
<1>构造器方法
<2>length()
<3>isEmpty()
<4>charAt(int index)
<5>codePointAt(int index)

1.构造器方法
 注意:该篇接上篇(一)的构造器方法。

//<1>根据byte数组、偏移量和偏移数量,用平台默认的字符集来生成新的字符串
//byte[]:byte数组,用于解码成字符串
//offset:偏移量,既数组的下标
//length:偏移数量,若为0,则表示没有偏移,返回空字符串
public String(byte bytes[], int offset, int length) {
    //检查数组边界
   checkBounds(bytes, offset, length);
    this.value = StringCoding.decode(bytes, offset, length);
}

//<2>将byte数组用平台默认的字符集来生成新的字符串
//byte[]:byte数组,用于解码成字符串
public String(byte bytes[]) {
    this(bytes, 0, bytes.length);
}

//<3>根据StringBuffer参数中的字符顺序来生成一个新的String对象
//buffer:StringBuffer对象,其缓冲区放置的是字符顺序内容
public String(StringBuffer buffer) {
  //加锁,用于避免buffer被别的线程修改而造成生成的String是错误的
  synchronized(buffer) {
       this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
   }
}

//<4>根据StringBuilder参数中的字符顺序来生成一个新的String对象
//builder:StringBuilder对象,其缓冲区放置的是字符顺序内容
public String(StringBuilder builder) {
    //没有加锁,所以是线程不安全,但是相比StringBuffer而言,效率更快
    this.value = Arrays.copyOf(builder.getValue(), builder.length());
}

//<5>根据传进来的字符数组来设置String类的value数组
//(1)直接给数组赋值(相当于直接将String的value的指针指向char[]数组),比浅拷贝快
//(2)共享内部数组节约内存。
//权限为包范围是因为一旦该方法设置为公有,在外面可以访问的话,就破坏了字符串的不可变性。
//value:字符数组
//share:无用参数,目前不支持false操作。默认为true操作
String(char[] value, boolean share) {
   // assert share : "unshared not supported";
    this.value = value;
}

 
2. length()方法
 该方法常用于确定字符串的长度。

public int length() {
    return value.length;
}

基本属性:public公有
返回值:int

该方法的主要作用是:返回字符串的长度,更精准地将是返回字符串的Unicode的数量。大部分情况下,一个字符是一个Unicode,但存在一些特殊的字符是两个Unicode。
 

3.isEmpty()方法
 String的方法,用于判断String对象是否为空字符串:

public boolean isEmpty() {
  return value.length == 0;
}

基本属性:public公有
返回值:boolean
返回值说明:如果String对象的长度为0则返回true,否则返回false

注意:该方法要保证String对象不为null,如果String对象为null,则会抛出NullPointerException(空指针异常)
 
4. charAt(int index)方法

//正确返回时,返回下标为index的char字符
public char charAt(int index) {
    //如果超出范围则抛出字符串角标越界异常
    if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return value[index];
}

基本属性:public公有
返回值:char
返回值说明:返回某个字符,根据参数来决定。
index:取值为0到字符串长度-1的范围之间。既下标位置。

该方法的主要作用是:返回字符串的第【index+1】个位置的字符。
 
5. codePointAt(int index)方法

//正确返回时,返回下标为index的char字符的Unicode的解码值
public int codePointAt(int index) {
  if ((index < 0) || (index >= value.length)) {
        throw new StringIndexOutOfBoundsException(index);
    }
    return Character.codePointAtImpl(value, index, value.length);
}

基本属性:public公有
返回值:int
返回值说明:返回char字符的Unicode解码值,字符根据参数来决定。
index:取值为0到字符串长度-1的范围之间。既下标位置。

该方法的主要作用是:返回字符的Unicode的解码值。

猜你喜欢

转载自blog.csdn.net/pseudonym_/article/details/80267418