@ -52,8 +52,7 @@ final class ProtobufArrayList<E> extends AbstractProtobufList<E> implements Rand
ensureIsMutable ( ) ;
ensureIsMutable ( ) ;
if ( size = = array . length ) {
if ( size = = array . length ) {
// Resize to 1.5x the size
int length = growSize ( size ) ;
int length = ( ( size * 3 ) / 2 ) + 1 ;
E [ ] newArray = Arrays . copyOf ( array , length ) ;
E [ ] newArray = Arrays . copyOf ( array , length ) ;
array = newArray ;
array = newArray ;
@ -65,6 +64,11 @@ final class ProtobufArrayList<E> extends AbstractProtobufList<E> implements Rand
return true ;
return true ;
}
}
private static int growSize ( int previousSize ) {
// Resize to 1.5x the size
return ( ( previousSize * 3 ) / 2 ) + 1 ;
}
@Override
@Override
public void add ( int index , E element ) {
public void add ( int index , E element ) {
ensureIsMutable ( ) ;
ensureIsMutable ( ) ;
@ -77,8 +81,7 @@ final class ProtobufArrayList<E> extends AbstractProtobufList<E> implements Rand
// Shift everything over to make room
// Shift everything over to make room
System . arraycopy ( array , index , array , index + 1 , size - index ) ;
System . arraycopy ( array , index , array , index + 1 , size - index ) ;
} else {
} else {
// Resize to 1.5x the size
int length = growSize ( size ) ;
int length = ( ( size * 3 ) / 2 ) + 1 ;
E [ ] newArray = createArray ( length ) ;
E [ ] newArray = createArray ( length ) ;
// Copy the first part directly
// Copy the first part directly
@ -132,6 +135,21 @@ final class ProtobufArrayList<E> extends AbstractProtobufList<E> implements Rand
return size ;
return size ;
}
}
/** Ensures the backing array can fit at least minCapacity elements. */
void ensureCapacity ( int minCapacity ) {
if ( minCapacity < = array . length ) {
return ;
}
// To avoid quadratic copying when calling .addAllFoo(List) in a loop, we must not size to
// exactly the requested capacity, but must exponentially grow instead. This is similar
// behaviour to ArrayList.
int n = size ;
while ( n < minCapacity ) {
n = growSize ( n ) ;
}
array = Arrays . copyOf ( array , n ) ;
}
@SuppressWarnings ( "unchecked" )
@SuppressWarnings ( "unchecked" )
private static < E > E [ ] createArray ( int capacity ) {
private static < E > E [ ] createArray ( int capacity ) {
return ( E [ ] ) new Object [ capacity ] ;
return ( E [ ] ) new Object [ capacity ] ;