@ SuppressWarnings ( "unchecked" ) static < T > T [ ] finishToArray ( T [ ] array , Iterator < ? > it ) { T [ ] rp = array ; int i = rp . length ; while ( it . hasNext ( ) ) { final int cap = rp . length ; if ( i == cap ) { int newCap = ( ( cap / 2 ) + 1 ) * 3 ; if ( newCap <= cap ) { // integer overflow if ( cap == Integer . MAX_VALUE ) { throw new OutOfMemoryError ( ) ; } newCap = Integer . MAX_VALUE ; } rp = Arrays . copyOf ( rp , newCap ) ; } rp [ ++ i ] = ( T ) it . next ( ) ; } // trim if overallocated return ( i == rp . length ) ? rp : Arrays . copyOf ( rp , i ) ; }
Reallocates the array being used within toArray when the iterator returned more elements than expected and finishes filling it from the iterator .