String源码阅读第一天

public final class String
    implements java.io.Serializable, Comparable, CharSequence {
    /** 保存定义的值 */
    private final char value[];

    /** 缓存字符串的hash code */
    private int hash; // Default to 0

    /** 序列化 */
    private static final long serialVersionUID = -6849794470754667710L;

    /** 这个字段目前不知道干啥的 */
    private static final ObjectStreamField[] serialPersistentFields =
        new ObjectStreamField[0];

    /** 生成一个空的字符串 */
    public String() {
        this.value = "".value;
    }

    /** 生成指定字符串 */
    public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }

    /** 传入一个char数组并拷贝到当前对象 */
    public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }
    /** 
      传入一个char数组,一个开始下标,一个长度。
      返回从offset下标开始到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);
        }
        this.value = Arrays.copyOfRange(value, offset, offset+count);
    }

测试

    public static void main(String[] args) {

        String str = new String();
        System.out.println(str);//


        String str = new String("looveh");
        System.out.println(str);//looveh


        char[] value = {'l','o','o','v','e','h'};
        String str = new String(value,1,4);
        System.out.println(str);//oove
    }

你可能感兴趣的:(String源码阅读第一天)