work hard work smart

专注于Java后端开发。 不断总结,举一反三。
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

String源码解析

Posted on 2020-04-12 12:29  work hard work smart  阅读(193)  评论(0编辑  收藏  举报

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);