美文网首页
String源码观后感

String源码观后感

作者: 楚朝伟 | 来源:发表于2018-10-22 15:07 被阅读0次

String 是开发中最常用的类之一了。今天看看string的源码,String里面都有啥。

   private final char value[];

public String() { this.value = "".value }

public String(String original) {
        this.value = original.value;
        this.hash = original.hash;
    }
 public String(char value[]) {
        this.value = Arrays.copyOf(value, value.length);
    }

String 有多种构造方法,这里就不一一粘出来了。 先看这两段代码,我们可以看到 String的底层是个char类型的数组。由于被final修饰过,就无法被修改。
当我们创造一个string类型的数据时,无论怎么操作 最后他的值是不会变的。

下面这个构成方法的入参 是一个char类型的数组,起始索引,长度。
这个方法做的是把旧的数组截取后,放到新的数组中。我们可以看到arraycopy()方法被native修饰过。这表示底层调用的是c语言的代码了。

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 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;
    }
 public static native void arraycopy(Object src,  int  srcPos,
                                        Object dest, int destPos,
                                        int length);

这里说下 当入参是stringbuffer 是线程安全的 而stringbuilder 是没有加同步的

public String(StringBuffer buffer) {
        synchronized(buffer) {
            this.value = Arrays.copyOf(buffer.getValue(), buffer.length());
        }
    }

public String(StringBuilder builder) {
        this.value = Arrays.copyOf(builder.getValue(), builder.length());
    }

相关文章

网友评论

      本文标题:String源码观后感

      本文链接:https://www.haomeiwen.com/subject/ewiszftx.html