java - StringBuffer 的 insert() 和 deleteCharAt() 方法是如何工作的

标签 java string stringbuilder stringbuffer

<分区>

在 Java 中,StringBuffer()StringBuilder() 中有称为 insert()deleteCharAt() 我很想多了解一下这两种具体方法的工作原理。或者如何使用标准的 java String 方法编写程序。我认为它们是您自己编写的非常简单的方法?

最佳答案

在 Sun 的实现中,这两个方法都委托(delegate)给 StringBuffer 的父类 AbstractStringBuilder:

public synchronized StringBuffer insert(int index, char str[], int offset,
                                        int len) 
{
    super.insert(index, str, offset, len);
    return this;
}

public synchronized StringBuffer deleteCharAt(int index) {
    super.deleteCharAt(index);
    return this;
}

AbstractStringBuffer 有以下实现:

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;
}

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;
}

所以,没什么特别的。

关于java - StringBuffer 的 insert() 和 deleteCharAt() 方法是如何工作的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12551885/

相关文章:

java - 从语言类获取语言

java - 如何给java添加第三方java库

c# - 获取字符串中某个索引后第一个检测到的空间的索引

java - Base64 值导致 SAX 解析器中的 StringBuilder.append 内存不足错误

java - 如何在Android中每2个字符后连接特殊符号作为冒号

java - 作为一个新手,我找不到程序中的错误

java - HTTP 状态 404 – 始终返回未找到

c++ - 将 ifstream 中的一行读入字符串变量

Java字符串函数不能被调用,因为它不是静态的

JAVA追加stringbuilder到textarea,不替换textarea只是添加到它(需要替换而不是添加)