美文网首页
JDK源码解析<三> java.lang.AbstractStr

JDK源码解析<三> java.lang.AbstractStr

作者: 小吖么小一郎 | 来源:发表于2019-07-08 15:05 被阅读0次

    可变性

    1. AbstractStringBuilder中变量:char value[]; int count; 都不是final修饰的,并且也定义了getValues方法让我们可以直接拿到value[],value实际上是个动态数组。

    方法

    1. public int length(): 返回已经存储的实际长度(就是count值)
    2. public int capacity(): capacity是’容量’的意思,得到目前该value数组的实际大小
    3. ensureCapacity(int minimumCapacity): 确保value数组的容量是否够用,如果不够用,调用expandCapacity(minimumCapacity)方法扩容,参数为需要的容量
     public void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > value.length) {
            expandCapacity(minimumCapacity);
        }
      }
    
    1. expandCapacity(int minimumCapacity):对数组进行扩容,参数为需要的容量
     void expandCapacity(int minimumCapacity) {
        int newCapacity = (value.length + 1) * 2;
            if (newCapacity < 0) {
                newCapacity = Integer.MAX_VALUE;
            } else if (minimumCapacity > newCapacity) {
            newCapacity = minimumCapacity;
        }
            value = Arrays.copyOf(value, newCapacity);
    }
    
    扩容的算法: 
    如果调用了该函数,说明容量不够用了,先将当前容量+1的二倍(newCapacity)与需要的容量(minimumCapacity)比较。 
    如果比需要的容量大,那就将容量扩大到容量+1的二倍;如果比需要的容量小,那就直接扩大到需要的容量。 
    使用Arrays.copyOf()这个非常熟悉的方法来使数组容量动态扩大
    
    1. public void trimToSize(): 如果value数组的容量有多余的,那么就把多余的全部都释放掉
    2. setLength(int newLength):强制增大实际长度count的大小,容量如果不够就用 expandCapacity()扩大;将扩大的部分全部用’\0’(ASCII码中的null)来初始化
     public void setLength(int newLength) {
        if (newLength < 0)  throw new StringIndexOutOfBoundsException(newLength);
        if (newLength > value.length)  expandCapacity(newLength);
        if (count < newLength) {
            for (; count < newLength; count++)
            value[count] = '\0';
        } else {
                count = newLength;
            }
    }
    
    1. public char charAt(int index): 得到下标为index的字符
    2. public int codePointAt(int index): 得到代码点
    3. public void getChars(int srcBegin, int srcEnd, char dst[],int dstBegin): 将value[]的[srcBegin, srcEnd)拷贝到dst[]数组的desBegin开始处
    4. public String substring(int start) / public String substring(int start, int end) 得到子字符串
    5. public CharSequence subSequence(int start, int end): 得到一个子字符序列
    6. reverse():将value给倒序存放(注意改变的就是本value,而不是创建了一个新的AbstractStringBuilder然后value为倒序)
    public AbstractStringBuilder reverse() {
        boolean hasSurrogate = false;
        int n = count - 1;
        for (int j = (n-1) >> 1; j >= 0; --j) {
            char temp = value[j];
            char temp2 = value[n - j];
            if (!hasSurrogate) {
            hasSurrogate = (temp >= Character.MIN_SURROGATE && temp <= Character.MAX_SURROGATE)
                || (temp2 >= Character.MIN_SURROGATE && temp2 <= Character.MAX_SURROGATE);
            }
            value[j] = temp2;
            value[n - j] = temp;
        }
        if (hasSurrogate) {
            // Reverse back all valid surrogate pairs
            for (int i = 0; i < count - 1; i++) {
            char c2 = value[i];
            if (Character.isLowSurrogate(c2)) {
                char c1 = value[i + 1];
                if (Character.isHighSurrogate(c1)) {
                value[i++] = c1;
                value[i] = c2;
                }
            }
            }
        }
        return this;
    }
    
    1. public abstract String toString(); 唯一的一个抽象方法:toString()
    2. public void setCharAt(int index, char ch): 直接设置下标为index的字符为ch
    3. public AbstractStringBuilder replace(int start, int end, String str): 用字符串str替换掉value[]数组的[start,end)部分
    4. append都表示’追加’,insert都表示’插入
    // 利用Object(或任何对象)的toString方法转成字符串然后添加到该value[]中
    public AbstractStringBuilder append(Object obj) {
       return append(String.valueOf(obj));
       }
    
    // append(String str)/append(StringBuffer sb)/append(CharSequence s)。直接修改value[],并且’添加’的意思为链接到原value[]的实际count的后面
    // 同时注意返回的都是AbstractStringBuilder,意味着append方法可以连续无限调用,即AbstractStringBuilder对象.append(参数1).append(参数2).append(参数三)…………;
     public AbstractStringBuilder append(String str) {
        if (str == null) str = "null";
            int len = str.length();
        if (len == 0) return this;
        int newCount = count + len;
        if (newCount > value.length)
            expandCapacity(newCount);
        str.getChars(0, len, value, count);
        count = newCount;
        return this;
        }
        // Documentation in subclasses because of synchro difference
        public AbstractStringBuilder append(StringBuffer sb) {
        if (sb == null)
                return append("null");
        int len = sb.length();
        int newCount = count + len;
        if (newCount > value.length)
            expandCapacity(newCount);
        sb.getChars(0, len, value, count);
        count = newCount;
        return this;
        }
        // Documentation in subclasses because of synchro difference
        public AbstractStringBuilder append(CharSequence s) {
            if (s == null)
                s = "null";
            if (s instanceof String)
                return this.append((String)s);
            if (s instanceof StringBuffer)
                return this.append((StringBuffer)s);
            return this.append(s, 0, s.length());
        }
    
    1. public AbstractStringBuilder append(CharSequence s, int start, int end):添加字符序列s的部分序列,范围是[start,end)
    2. public AbstractStringBuilder append(char str[]):添加一个字符数组
    3. public AbstractStringBuilder append(char str[], int offset, int len):添加一个字符数组的一部分,该部分的范围是[offset,offset+len);
    4. public AbstractStringBuilder append(boolean b):添加布尔值。
    5. public AbstractStringBuilder append(char c):添加一个字符
    6. public AbstractStringBuilder append(int i):添加一个整数'
    7. public AbstractStringBuilder append(long l):添加一个长整型的数据,原理同上一个append
    8. public AbstractStringBuilder append(float f)/append(double d):添加一个浮点数。
    9. (insert的核心代码)在value[]的下标为index位置插入数组str的一部分,该部分的范围为:[offset,offset+len);
     public AbstractStringBuilder insert(int index, char str[], int offset,int len){
            if ((index < 0) || (index > length()))
            throw new StringIndexOutOfBoundsException(index);
            if ((offset < 0) || (len < 0) || (offset > str.length - len))
                throw new StringIndexOutOfBoundsException(
                    "offset " + offset + ", len " + len + ", str.length " 
                    + str.length);
        int newCount = count + len;
        if (newCount > value.length)
            expandCapacity(newCount);
        System.arraycopy(value, index, value, index + len, count - index);
        System.arraycopy(str, offset, value, index, len);
        count = newCount;
        return this;
    }
    
    // insert(int offset, Object obj):在value[]的offset位置插入Object(或者说所有对象)的String版
    public AbstractStringBuilder insert(int offset, Object obj) {
        return insert(offset, String.valueOf(obj));
    }
    
    // insert(int offset, String str):在value[]的offset位置插入字符串
    public AbstractStringBuilder insert(int offset, String str) {
        if ((offset < 0) || (offset > length()))
            throw new StringIndexOutOfBoundsException(offset);
        if (str == null)
            str = "null";
        int len = str.length();
        int newCount = count + len;
        if (newCount > value.length)
            expandCapacity(newCount);
        System.arraycopy(value, offset, value, offset + len, count - offset);
        str.getChars(value, offset);
        count = newCount;
        return this;
    }
    
    //  insert(int offset, char str[]):在value[]的offset位置插入字符数组
    public AbstractStringBuilder insert(int offset, char str[]) {
        if ((offset < 0) || (offset > length()))
            throw new StringIndexOutOfBoundsException(offset);
        int len = str.length;
        int newCount = count + len;
        if (newCount > value.length)
            expandCapacity(newCount);
        System.arraycopy(value, offset, value, offset + len, count - offset);
        System.arraycopy(str, 0, value, offset, len);
        count = newCount;
        return this;
    }
    
    //  insert(int dstOffset, CharSequence s)/insert(int dstOffset, CharSequence s,int start, int end):插入字符序列
    public AbstractStringBuilder insert(int dstOffset, CharSequence s) {
            if (s == null)
                s = "null";
            if (s instanceof String)
                return this.insert(dstOffset, (String)s);
            return this.insert(dstOffset, s, 0, s.length());
    }
    public AbstractStringBuilder insert(int dstOffset, CharSequence s,
                                               int start, int end) {
            if (s == null)
                s = "null";
        if ((dstOffset < 0) || (dstOffset > this.length()))
            throw new IndexOutOfBoundsException("dstOffset "+dstOffset);
        if ((start < 0) || (end < 0) || (start > end) || (end > s.length()))
                throw new IndexOutOfBoundsException(
                    "start " + start + ", end " + end + ", s.length() " 
                    + s.length());
        int len = end - start;
            if (len == 0)
                return this;
        int newCount = count + len;
        if (newCount > value.length)
            expandCapacity(newCount);
        System.arraycopy(value, dstOffset, value, dstOffset + len,
                             count - dstOffset);
        for (int i=start; i<end; i++)
                value[dstOffset++] = s.charAt(i);
        count = newCount;
            return this;
    }
    
    // 插入基本类型:除了char是直接插入外,其他都是先转成String,然后调用编号为28的insert方法
    public AbstractStringBuilder insert(int offset, boolean b) {
        return insert(offset, String.valueOf(b));
    }
    public AbstractStringBuilder insert(int offset, char c) {
        int newCount = count + 1;
        if (newCount > value.length)
            expandCapacity(newCount);
        System.arraycopy(value, offset, value, offset + 1, count - offset);
        value[offset] = c;
        count = newCount;
        return this;
    }
    public AbstractStringBuilder insert(int offset, int i) {
        return insert(offset, String.valueOf(i));
    }
    public AbstractStringBuilder insert(int offset, long l) {
        return insert(offset, String.valueOf(l));
    }
    public AbstractStringBuilder insert(int offset, float f) {
        return insert(offset, String.valueOf(f));
    }
    public AbstractStringBuilder insert(int offset, double d) {
        return insert(offset, String.valueOf(d));
    }
    
    1. delete
    //  删掉value数组的[start,end)部分,并将end后面的数据移到start位置
     public AbstractStringBuilder delete(int start, int end) {
        if (start < 0)
            throw new StringIndexOutOfBoundsException(start);
        if (end > count)
            end = count;
        if (start > end)
            throw new StringIndexOutOfBoundsException();
            int len = end - start;
            if (len > 0) {
                System.arraycopy(value, start+len, value, start, count-end);
                count -= len;
            }
            return this;
    }
    
    //  删除下标为index的数据,并将后面的数据前移一位
     public AbstractStringBuilder deleteCharAt(int index) {
            if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        System.arraycopy(value, index+1, value, index, count-index-1);
        count--;
            return this;
    }
    
    1. query
    //  在value[]中找字符串str,若能找到,返回第一个字符串的第一个字符的下标
     public int indexOf(String str) {
        return indexOf(str, 0);
    }
    
    //  从fromIndex开始,在value[]中找字符串str,若能找到,返回第一个字符串的第一个字符的下标
    public int indexOf(String str, int fromIndex) {
            return String.indexOf(value, 0, count,
                                  str.toCharArray(), 0, str.length(), fromIndex);
    }
    
    //  从后往前找
    public int lastIndexOf(String str) {
            return lastIndexOf(str, count);
    }
    
    //  从后往前到fromIndex,找子串str
    public int lastIndexOf(String str, int fromIndex) {
            return String.lastIndexOf(value, 0, count,
                                  str.toCharArray(), 0, str.length(), fromIndex);
    }
    

    相关文章

      网友评论

          本文标题:JDK源码解析<三> java.lang.AbstractStr

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