public static int oversize ( int minTargetSize , int bytesPerElement ) { if ( minTargetSize < 0 ) { // catch usage that accidentally overflows int throw new IllegalArgumentException ( "invalid array size " + minTargetSize ) ; } if ( minTargetSize == 0 ) { // wait until at least one element is requested return 0 ; } // asymptotic exponential growth by 1/8th, favors // spending a bit more CPU to not tie up too much wasted // RAM: int extra = minTargetSize >> 3 ; if ( extra < 3 ) { // for very small arrays, where constant overhead of // realloc is presumably relatively high, we grow // faster extra = 3 ; } int newSize = minTargetSize + extra ; // add 7 to allow for worst case byte alignment addition below: if ( newSize + 7 < 0 ) { // int overflowed -- return max allowed array size return Integer . MAX_VALUE ; } if ( JRE_IS_64BIT ) { // round up to 8 byte alignment in 64bit env switch ( bytesPerElement ) { case 4 : // round up to project of 2 return ( newSize + 1 ) & 0x7ffffffe ; case 2 : // round up to project of 4 return ( newSize + 3 ) & 0x7ffffffc ; case 1 : // round up to project of 8 return ( newSize + 7 ) & 0x7ffffff8 ; case 8 : // no rounding default : // odd (invalid?) size return newSize ; } } else { // round up to 4 byte alignment in 64bit env switch ( bytesPerElement ) { case 2 : // round up to project of 2 return ( newSize + 1 ) & 0x7ffffffe ; case 1 : // round up to project of 4 return ( newSize + 3 ) & 0x7ffffffc ; case 4 : case 8 : // no rounding default : // odd (invalid?) size return newSize ; } } }
Returns an array size > = minTargetSize generally over - allocating exponentially to achieve amortized linear - time cost as the array grows .