1

在 Java 中,有两种方法StringBuffer()或被StringBuilder()调用方法insert()deleteCharAt()我很想进一步了解这两种特定方法是如何工作的。或者如何使用标准的 java String 方法进行编程。我认为它们是编写自己的非常简单的方法?

4

3 回答 3

4

在 Sun 的实现中,这两种方法都委托给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;
}

所以,没什么特别的。

于 2012-09-23T11:36:54.837 回答
2

insert(…)StringBuilder 和 StringBuffer的方法都使用简单的数组复制实现AbstractStringBuilder.insert(int, String)

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();
    ensureCapacityInternal(count + len);
    System.arraycopy(value, offset, value, offset + len, count - offset);
    str.getChars(value, offset);
    count += len;
    return this;
}

首先,它确保内部char []数组足够大以存储结果,然后使用给定的字符串将插入点之后的字符向右移动System.arraycopy(…)并覆盖从插入点开始的字符。

同样,deleteCharAt(int)StringBuilder 和 StringBuffer 的方法调用AbstractStringBuilder.deleteCharAt(int)

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

使用System.arraycopy(…)相反的方法删除一个字符:这次删除点之后的字符向左移动一个字符。

于 2012-09-23T11:37:14.463 回答
0

根据javadoc,两个类对它们的方法都说了同样的话。Insert 根据输入将字符串插入到字符串中。CharArray 添加基于 CharArray 的字符串等。DeleteCharAt 删除字符串中某个部分的字符。

StringBuffer 快一点,但 StringBuilder 更新。2

标准的 java String 方法不包含 deleteCharAt() 或 insert()(这就是 StringBuilder/Buffer 存在的原因),但您可能可以通过 substring() 找到解决方法。

是的,您可以自己编写方法。我会查看 JDK 中 StringBuilder 或 StringBuilder 的源代码。

于 2012-09-23T11:38:06.957 回答