• Java 源码 AbstractStringBuilder 抽象类


    介绍

    A mutable sequence of characters.

    示例

    xxxxxx

    结构

    源码

    成员变量

    /**
     * The value is used for character storage.
     */
    char[] value;
    
    /**
     * The count is the number of characters used.
     */
    int count;
    
    /**
     * The maximum size of array to allocate.
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    

    构造方法

    /**
     * Creates an AbstractStringBuilder of the specified capacity.
     */
    AbstractStringBuilder(int capacity) {
        value = new char[capacity];
    }
    

    成员方法

    /**
     * Appends the specified string to this character sequence.
     */
    public AbstractStringBuilder append(String str) {
      if (str == null)
        return appendNull();
      int len = str.length();
      ensureCapacityInternal(count + len);
      str.getChars(0, len, value, count);
      count += len;
      return this;
    }
    
    /**
     * Ensures that the capacity is at least equal to the specified minimum.
     */
    private void ensureCapacityInternal(int minimumCapacity) {
      if (minimumCapacity - value.length > 0) {
        value = Arrays.copyOf(value, newCapacity(minimumCapacity));
      }
    }
    
    /**
     * Returns a capacity at least as large as the given minimum capacity.
     */
    private int newCapacity(int minCapacity) {
      int newCapacity = (value.length << 1) + 2;
      if (newCapacity - minCapacity < 0) {
        newCapacity = minCapacity;
      }
      return (newCapacity <= 0 || MAX_ARRAY_SIZE - newCapacity < 0)
        ? hugeCapacity(minCapacity)
        : newCapacity;
    }
    
    private int hugeCapacity(int minCapacity) {
      if (Integer.MAX_VALUE - minCapacity < 0) { // overflow
        throw new OutOfMemoryError();
      }
      return (minCapacity > MAX_ARRAY_SIZE)
        ? minCapacity : MAX_ARRAY_SIZE;
    }
    

    面试

    Stringbuffer 与 Stringbuilder 的区别?
    1、StringBuffer:线程安全,StringBuilder:线程不安全,因为 StringBuffer 的所有公开方法都是 synchronized 修饰的。
    2、都继成了 AbstractStringBuilder 这个抽象类,实现了 CharSequence 接口。
    3、初始容量都是16和扩容机制都是"旧容量*2+2"。
    4、StringBuffer 比 StringBuilder 多了一个 toStringCache 字段,用来在 toString方法中进行缓存。

  • 相关阅读:
    Master公式计算递归时间复杂度
    对数器的使用
    HTML翻转菜单练习
    剑指offer题目解答合集(C++版)
    HTML---仿网易新闻登录页
    两个有序数组中的中位数以及求第k个最小数的值
    算法之重建二叉树
    AFNetWorking 上传功能使用及源码分析
    图片Alpha预乘的作用[转]
    C#/.NET 学习之路——从入门到放弃
  • 原文地址:https://www.cnblogs.com/feiqiangsheng/p/15906193.html
Copyright © 2020-2023  润新知