AbstractStringBuilder源码

news2025/2/28 12:08:47

介绍

AbstractStringBuilder这个抽象类是StringBuilder和StringBuffer的直接父类,而且定义了很多方法,因此在学习这两个类之前建议先学习 AbstractStringBuilder抽象类

该类在源码中注释是以JDK1.5开始作为前两个类的父类存在的

abstract class AbstractStringBuilder implements Appendable, CharSequence

image-20230523071729335

实现了两个接口,其中CharSequence这个字符序列的接口已经很熟悉了:

该接口规定了需要实现该字符序列的长度:length();

可以取得下标为index的的字符:charAt(int index);

可以得到该字符序列的一个子字符序列: subSequence(int start, int end);

规定了该字符序列的String版本(重写了父类Object的toString()):toString();

Appendable接口顾名思义,定义添加的’规则’:

append(CharSequence csq) throws IOException:如何添加一个字符序列

append(CharSequence csq, int start, int end) throws IOException:如何添加一个字符序列的一部分

append(char c) throws IOException:如何添加一个字符

常量&变量

    /**
     * The value is used for character storage.
     * 该字符序列的具体存储 没有被final修饰,表示可以不断扩容     
     */
    char[] value;

    /**
     * The count is the number of characters used.
     * 实际存储的数量
     */
    int count;
    
     /**
     * The maximum size of array to allocate (unless necessary).
     * Some VMs reserve some header words in an array.
     * Attempts to allocate larger arrays may result in
     * OutOfMemoryError: Requested array size exceeds VM limit
     * 最大数组长度
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

构造方法

    /**
     * This no-arg constructor is necessary for serialization of subclasses.
     */
    AbstractStringBuilder() {
    }

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

常用方法

length()

    /**
     * Returns the length (character count).
     *
     * @return  the length of the sequence of characters currently
     *          represented by this object
     *          返回已经存储的实际长度(就是count值)
     */
    @Override
    public int length() {
        return count;
    }

capacity()

    /**
     * Returns the current capacity. The capacity is the amount of storage
     * available for newly inserted characters, beyond which an allocation
     * will occur.
     *
     * @return  the current capacity
     * 得到目前该value数组的实际大小
     */
    public int capacity() {
        return value.length;
    }

ensureCapacity

    /**
     * Ensures that the capacity is at least equal to the specified minimum.
     * If the current capacity is less than the argument, then a new internal
     * array is allocated with greater capacity. The new capacity is the
     * larger of:
     * <ul>
     * <li>The {@code minimumCapacity} argument.
     * <li>Twice the old capacity, plus {@code 2}.
     * </ul>
     * If the {@code minimumCapacity} argument is nonpositive, this
     * method takes no action and simply returns.
     * Note that subsequent operations on this object can reduce the
     * actual capacity below that requested here.
     *
     * @param   minimumCapacity   the minimum desired capacity.
     *  确保容量至少等于指定的最小值。如果当前容量小于参数,则分配一个具有更大容量的新数组
     *
     */
    public void ensureCapacity(int minimumCapacity) {
        if (minimumCapacity > 0)
            ensureCapacityInternal(minimumCapacity);
    }

    /**
     * For positive values of {@code minimumCapacity}, this method
     * behaves like {@code ensureCapacity}, however it is never
     * synchronized.
     * If {@code minimumCapacity} is non positive due to numeric
     * overflow, this method throws {@code OutOfMemoryError}.
     */
    private void ensureCapacityInternal(int minimumCapacity) {
        // overflow-conscious code
        //扩容的实现
        if (minimumCapacity - value.length > 0) {
           //拷贝一个minimumCapacity大小的新数组
            value = Arrays.copyOf(value,
                    newCapacity(minimumCapacity));
        }
    }
    
     /**
     * Returns a capacity at least as large as the given minimum capacity.
     * Returns the current capacity increased by the same amount + 2 if
     * that suffices.
     * Will not return a capacity greater than {@code MAX_ARRAY_SIZE}
     * unless the given minimum capacity is greater than that.
     *
     * @param  minCapacity the desired minimum capacity
     * @throws OutOfMemoryError if minCapacity is less than zero or
     *         greater than Integer.MAX_VALUE
     */
    private int newCapacity(int minCapacity) {
        // overflow-conscious code
        //新数组的容量
        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;
    }

trimToSize

    /**
     * Attempts to reduce storage used for the character sequence.
     * If the buffer is larger than necessary to hold its current sequence of
     * characters, then it may be resized to become more space efficient.
     * Calling this method may, but is not required to, affect the value
     * returned by a subsequent call to the {@link #capacity()} method.
     * 如果value数组的容量有多余的,那么就把多余的全部都释放掉
     */
    public void trimToSize() {
        //数组的长度大于当前存储的个数
        if (count < value.length) {
            //拷贝count大小的新数组
            value = Arrays.copyOf(value, count);
        }
    }

setLength

    /**
     * Sets the length of the character sequence.
     * The sequence is changed to a new character sequence
     * whose length is specified by the argument. For every nonnegative
     * index <i>k</i> less than {@code newLength}, the character at
     * index <i>k</i> in the new character sequence is the same as the
     * character at index <i>k</i> in the old sequence if <i>k</i> is less
     * than the length of the old character sequence; otherwise, it is the
     * null character {@code '\u005Cu0000'}.
     *
     * In other words, if the {@code newLength} argument is less than
     * the current length, the length is changed to the specified length.
     * <p>
     * If the {@code newLength} argument is greater than or equal
     * to the current length, sufficient null characters
     * ({@code '\u005Cu0000'}) are appended so that
     * length becomes the {@code newLength} argument.
     * <p>
     * The {@code newLength} argument must be greater than or equal
     * to {@code 0}.
     *
     * @param      newLength   the new length
     * @throws     IndexOutOfBoundsException  if the
     *               {@code newLength} argument is negative.
     *  强制增大实际长度count的大小,容量如果不够就用 expandCapacity()扩大;
     *  将扩大的部分全部用’\0’(ASCII码中的null)来初始化
     */
    public void setLength(int newLength) {
        if (newLength < 0)
            throw new StringIndexOutOfBoundsException(newLength);
        //判断是否需要扩容
        ensureCapacityInternal(newLength);

        if (count < newLength) {
            //填充数组
            Arrays.fill(value, count, newLength, '\0');
        }

        count = newLength;
    }

charAt

    /**
     * Returns the {@code char} value in this sequence at the specified index.
     * The first {@code char} value is at index {@code 0}, the next at index
     * {@code 1}, and so on, as in array indexing.
     * <p>
     * The index argument must be greater than or equal to
     * {@code 0}, and less than the length of this sequence.
     *
     * <p>If the {@code char} value specified by the index is a
     * <a href="Character.html#unicode">surrogate</a>, the surrogate
     * value is returned.
     *
     * @param      index   the index of the desired {@code char} value.
     * @return     the {@code char} value at the specified index.
     * @throws     IndexOutOfBoundsException  if {@code index} is
     *             negative or greater than or equal to {@code length()}.
     *             得到下标为index的字符
     */
    @Override
    public char charAt(int index) {
        if ((index < 0) || (index >= count))
            throw new StringIndexOutOfBoundsException(index);
        return value[index];
    }

codePointAt

    /**
     * Returns the character (Unicode code point) at the specified
     * index. The index refers to {@code char} values
     * (Unicode code units) and ranges from {@code 0} to
     * {@link #length()}{@code  - 1}.
     *
     * <p> If the {@code char} value specified at the given index
     * is in the high-surrogate range, the following index is less
     * than the length of this sequence, and the
     * {@code char} value at the following index is in the
     * low-surrogate range, then the supplementary code point
     * corresponding to this surrogate pair is returned. Otherwise,
     * the {@code char} value at the given index is returned.
     *
     * @param      index the index to the {@code char} values
     * @return     the code point value of the character at the
     *             {@code index}
     * @exception  IndexOutOfBoundsException  if the {@code index}
     *             argument is negative or not less than the length of this
     *             sequence.
     *            返回指定索引处的字符(Unicode码点)
     */
    public int codePointAt(int index) {
        if ((index < 0) || (index >= count)) {
            throw new StringIndexOutOfBoundsException(index);
        }
        return Character.codePointAtImpl(value, index, count);
    }

getChars

    /**
     * Characters are copied from this sequence into the
     * destination character array {@code dst}. The first character to
     * be copied is at index {@code srcBegin}; the last character to
     * be copied is at index {@code srcEnd-1}. The total number of
     * characters to be copied is {@code srcEnd-srcBegin}. The
     * characters are copied into the subarray of {@code dst} starting
     * at index {@code dstBegin} and ending at index:
     * <pre>{@code
     * dstbegin + (srcEnd-srcBegin) - 1
     * }</pre>
     *
     * @param      srcBegin   start copying at this offset.
     * @param      srcEnd     stop copying at this offset.
     * @param      dst        the array to copy the data into.
     * @param      dstBegin   offset into {@code dst}.
     * @throws     IndexOutOfBoundsException  if any of the following is true:
     *             <ul>
     *             <li>{@code srcBegin} is negative
     *             <li>{@code dstBegin} is negative
     *             <li>the {@code srcBegin} argument is greater than
     *             the {@code srcEnd} argument.
     *             <li>{@code srcEnd} is greater than
     *             {@code this.length()}.
     *             <li>{@code dstBegin+srcEnd-srcBegin} is greater than
     *             {@code dst.length}
     *             </ul>
     *             将value[]的[srcBegin, srcEnd)拷贝到dst[]数组的desBegin开始处
     */
    public void getChars(int srcBegin, int srcEnd, char[] dst, int dstBegin)
    {
        if (srcBegin < 0)
            throw new StringIndexOutOfBoundsException(srcBegin);
        if ((srcEnd < 0) || (srcEnd > count))
            throw new StringIndexOutOfBoundsException(srcEnd);
        if (srcBegin > srcEnd)
            throw new StringIndexOutOfBoundsException("srcBegin > srcEnd");
        System.arraycopy(value, srcBegin, dst, dstBegin, srcEnd - srcBegin);
    }

substring

     /**
     * Returns a new {@code String} that contains a subsequence of
     * characters currently contained in this character sequence. The
     * substring begins at the specified index and extends to the end of
     * this sequence.
     *
     * @param      start    The beginning index, inclusive.
     * @return     The new string.
     * @throws     StringIndexOutOfBoundsException  if {@code start} is
     *             less than zero, or greater than the length of this object.
     *   得到子字符串
     */
    public String substring(int start) {
        return substring(start, count);
    }
    
     /**
     * Returns a new {@code String} that contains a subsequence of
     * characters currently contained in this sequence. The
     * substring begins at the specified {@code start} and
     * extends to the character at index {@code end - 1}.
     *
     * @param      start    The beginning index, inclusive.
     * @param      end      The ending index, exclusive.
     * @return     The new string.
     * @throws     StringIndexOutOfBoundsException  if {@code start}
     *             or {@code end} are negative or greater than
     *             {@code length()}, or {@code start} is
     *             greater than {@code end}.
     */
    public String substring(int start, int end) {
        if (start < 0)
            throw new StringIndexOutOfBoundsException(start);
        if (end > count)
            throw new StringIndexOutOfBoundsException(end);
        if (start > end)
            throw new StringIndexOutOfBoundsException(end - start);
        return new String(value, start, end - start);
    }

subSequence

    /**
     * Returns a new character sequence that is a subsequence of this sequence.
     *
     * <p> An invocation of this method of the form
     *
     * <pre>{@code
     * sb.subSequence(begin,&nbsp;end)}</pre>
     *
     * behaves in exactly the same way as the invocation
     *
     * <pre>{@code
     * sb.substring(begin,&nbsp;end)}</pre>
     *
     * This method is provided so that this class can
     * implement the {@link CharSequence} interface.
     *
     * @param      start   the start index, inclusive.
     * @param      end     the end index, exclusive.
     * @return     the specified subsequence.
     *
     * @throws  IndexOutOfBoundsException
     *          if {@code start} or {@code end} are negative,
     *          if {@code end} is greater than {@code length()},
     *          or if {@code start} is greater than {@code end}
     * @spec JSR-51
     * 得到一个子字符序列
     */
    @Override
    public CharSequence subSequence(int start, int end) {
        return substring(start, end);
    }

reverse

    /**
     * Causes this character sequence to be replaced by the reverse of
     * the sequence. If there are any surrogate pairs included in the
     * sequence, these are treated as single characters for the
     * reverse operation. Thus, the order of the high-low surrogates
     * is never reversed.
     *
     * Let <i>n</i> be the character length of this character sequence
     * (not the length in {@code char} values) just prior to
     * execution of the {@code reverse} method. Then the
     * character at index <i>k</i> in the new character sequence is
     * equal to the character at index <i>n-k-1</i> in the old
     * character sequence.
     *
     * <p>Note that the reverse operation may result in producing
     * surrogate pairs that were unpaired low-surrogates and
     * high-surrogates before the operation. For example, reversing
     * "\u005CuDC00\u005CuD800" produces "\u005CuD800\u005CuDC00" which is
     * a valid surrogate pair.
     *
     * @return  a reference to this object.
     * 将value给倒序存放
     * (注意改变的就是本value,而不是创建了一个新的AbstractStringBuilder然后value为倒序)
     */
    public AbstractStringBuilder reverse() {
        boolean hasSurrogates = false;
        int n = count - 1;
        for (int j = (n-1) >> 1; j >= 0; j--) {
            int k = n - j;
            char cj = value[j];
            char ck = value[k];
            value[j] = ck;
            value[k] = cj;
            if (Character.isSurrogate(cj) ||
                Character.isSurrogate(ck)) {
                hasSurrogates = true;
            }
        }
        if (hasSurrogates) {
            reverseAllValidSurrogatePairs();
        }
        return this;
    }

github:AbstractStringBuilder源码

如文章有问题请留言,谢谢~

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/557439.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【已解决】使用selenium启动谷歌Chrome浏览器打开指定网站,页面空白,而使用其它浏览器手动打开该网站则正常

问题描述 1、在使用python实现自动化网络爬虫时&#xff0c;我使用到selenium来驱动谷歌Chrome浏览器来打开某一个网页&#xff0c;然后爬取数据&#xff0c;代码如下&#xff1a; from selenium import webdriver import timedriver webdriver.Chrome() driver.get(https://…

基于JavaSpringBoot+Vue+uniapp实现微信小程序新闻资讯平台

博主介绍&#xff1a;✌全网粉丝20W,csdn特邀作者、博客专家、CSDN新星计划导师、java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专…

多模态大模型时代下的文档图像智能分析与处理

多模态大模型时代下的文档图像智能分析与处理 0. 前言1. 人工智能发展历程1.1 传统机器学习1.2 深度学习1.3 多模态大模型时代 2. CCIG 文档图像智能分析与处理论坛2.1 文档图像智能分析与处理的重要性和挑战2.2 文档图像智能分析与处理高峰论坛2.3 走进合合信息 3. 文档图像智…

<SQL>《SQL命令(含例句)精心整理版(2)》

《SQL命令&#xff08;含例句&#xff09;精心整理版&#xff08;2&#xff09;》 跳转《SQL命令&#xff08;含例句&#xff09;精心整理版&#xff08;1&#xff09;8 函数8.1 文本处理函数8.2 数值处理函数8.3 时间处理函数8.3.1 时间戳转化为自定义格式from_unixtime8.3.2 …

案例17:Java代驾管理系统设计与实现开题报告

博主介绍&#xff1a;✌全网粉丝30W,csdn特邀作者、博客专家、CSDN新星计划导师、java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专…

类的加载过程

一、前言   类加载器的技术 二、类的加载过程 2.1 JVM将类加载过程分为三个步骤&#xff1a;装载&#xff08;Load&#xff09;&#xff0c;链接&#xff08;Link&#xff09;和初始化(Initialize)。链接又分为三个步骤&#xff0c;如下图所示&#xff1a; 装载&#xff1a;…

linux命名管道总结

FIFO&#xff0c;也称为命名管道&#xff0c;它是一种文件类型。 1、特点 (1)FIFO可以在无关的进程之间交换数据&#xff0c;与无名管道不同。 (2)FIFO有路径名与之相关联&#xff0c;它以一种特殊设备文件形式存在于文件系统中。 2、原型 (1)#include <sys/types.h> #in…

一篇文章告诉你什么是Java内存模型

在上篇 并发编程Bug起源:可见性、有序性和原子性问题&#xff0c;介绍了操作系统为了提示运行速度&#xff0c;做了各种优化&#xff0c;同时也带来数据的并发问题&#xff0c; 定义 在单线程系统中&#xff0c;代码按照顺序从上往下顺序执行&#xff0c;执行不会出现问题。比…

一图看懂 click 模块:一个通过组合的方式来创建精美命令行界面的包,资料整理+笔记(大全)

本文由 大侠(AhcaoZhu)原创&#xff0c;转载请声明。 链接: https://blog.csdn.net/Ahcao2008 一图看懂 click 模块&#xff1a;一个通过组合的方式来创建精美命令行界面的包&#xff0c;资料整理笔记&#xff08;大全&#xff09; &#x1f9ca;摘要&#x1f9ca;模块图&#…

Python篇——数据结构与算法(第一部分)

目录 一、查找 1、顺序查找&#xff1a;也叫线性查找&#xff0c;从列表第一个元素开始&#xff0c;顺序进行搜索&#xff0c;直到找到元素或搜索到列表最后一个元素为止。 2、二分查找&#xff1a;也叫折半查找&#xff0c;从有序列表的初始候选区li[0:n]开始&#xff0c;通…

【远程访问】Linux搭建SVN服务器,并内网穿透实现公网远程访问

文章目录 前言1. Ubuntu安装SVN服务2. 修改配置文件2.1 修改svnserve.conf文件2.2 修改passwd文件2.3 修改authz文件 3. 启动svn服务4. 内网穿透4.1 安装cpolar内网穿透4.2 创建隧道映射本地端口 5. 测试公网访问6. 配置固定公网TCP端口地址6.1 保留一个固定的公网TCP端口地址6…

C++入门预备语法

C入门预备语法 C关键字命名空间C输入&输出初步缺省参数函数重载引用内联函数auto和范围for&#xff08;C11&#xff09;指针空值nullptr C关键字 命名空间 命名空间是一种将变量名、函数名、类名和库名称等封装到一个命名空间域中&#xff0c;与其他域的同名量相隔离&…

【AUTOSAR】【以太网】SomeIpTp

目录 一、概述 二、限制与约束 三、功能说明 3.1 SOME/IP帧头 3.1.1 消息类型字段 3.1.2 偏移字段 3.1.3 更多段标志 3.1.4 示例 3.2 错误分类 3.2.1 开发错误 3.2.2 运行错误 四、API接口 4.1 API定义 4.2 回调接口 4.3 调度接口 一、概述 规范规定了AUTOSAR 基…

知识付费:创客匠人的发展转型之路

互联网时代到来后&#xff0c;知识付费行业以极快的速度崛起&#xff0c;让最早入局的人赚得盆满钵满&#xff0c;同时&#xff0c;也有很多人想进入行业发展&#xff0c;却没有真正打造好自己的平台&#xff0c;无法形成系统成熟的企业。如今&#xff0c;行业发展趋势还在不断…

案例19:Java私房菜定制上门服务系统设计与实现开题报告

博主介绍&#xff1a;✌全网粉丝30W,csdn特邀作者、博客专家、CSDN新星计划导师、java领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java技术领域和毕业项目实战✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精彩专…

小型双轮差速底盘实现红外避障功能

1. 功能说明 在R023e机器人车体上安装1个近红外传感器&#xff0c;实现机器人小车避障功能。 2. 电子硬件 在这个示例中&#xff0c;我们采用了以下硬件&#xff0c;请大家参考&#xff1a; 主控板 Basra主控板&#xff08;兼容Arduino Uno&#xff09; 扩展板 Bigfish2.1扩展板…

VS2022 CUDA环境配置

文章目录 安装准备新建项目 安装准备 配置Cuda环境主要分为以下几个步骤 安装VS 这个应该不用太说&#xff0c;直接装最新版安装CUDA 下载地址&#xff1a;Cuda Toolkit安装cuDNN 下载地址&#xff1a;cuDNN archieve 这个安装顺序非常重要&#xff0c;一定是先装VS后装CUDA…

19 # promisify:将回调方法 promise 化

之前写个单独的方法去处理文件读取 function read(filename) {return new Promise((resolve, reject) > {fs.readFile(filename, "utf-8", function (err, data) {if (err) reject(err);resolve(data);});}); }将 node 的 api 快速的转化成 promise 的形式 cons…

Linux基于Apache服务搭建简易镜像站

&#x1f497;wei_shuo的个人主页 &#x1f4ab;wei_shuo的学习社区 &#x1f310;Hello World &#xff01; Linux基于Apache服务搭建简易镜像站 安装Apache服务器 yum install -y httpd.x86_64 配置Apache服务器&#xff1a;编辑Apache配置文件/etc/httpd/conf/httpd.conf #S…

深度学习 - 50.推荐场景下的 Attention And Multi-Head Attention

目录 一.引言 二.Attention 1.Common Attention 2.Google Attention 三.Multi-Head Attention 四.总结 一.引言 Attention 注意力机制最早来源于我们自身的视觉感官&#xff0c;当我们视觉获取到图像信息时&#xff0c;我们并不是从前往后从上往下均匀的扫描画面&#x…