Search code examples
javastringstringbuilderstringbuffer

How do the StringBuffer insert() and deleteCharAt() methods work


In Java there is methods in either StringBuffer() or StringBuilder() called insert() and deleteCharAt() I am very interested in understanding a little more how these two specific methods work. Or how one would program one using the standard java String methods. I reckon they are pretty simple methods to write yourself?


Solution

  • In the Sun's implementation both methods are delegated to StringBuffer's parent class 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 has the following implementations:

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

    So, nothing special.