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