@@ -143,24 +143,27 @@ private void lazyInit(int pageIndex) {
143143
144144 private void shiftPagesRight (int pageIndex ) {
145145 int requiredExtension = minPageIndex - pageIndex ;
146- // check if there is space to shift into
147- boolean canShiftRight = true ;
148- for (int i = 0 ; i < requiredExtension && canShiftRight ; ++i ) {
149- canShiftRight = null == pages [pages .length - i - 1 ];
150- }
151- if (canShiftRight ) {
152- System .arraycopy (pages , 0 , pages , requiredExtension , pages .length - requiredExtension );
153- } else {
154- double [][] newPages = new double [pages .length + aligned (requiredExtension )][];
155- System .arraycopy (pages , 0 , newPages , requiredExtension , pages .length );
156- this .pages = newPages ;
146+ if (requiredExtension > 0 ) {
147+ // check if there is space to shift into
148+ boolean canShiftRight = true ;
149+ // check if there are enough null slots at the end of the array to shift into
150+ for (int i = 0 ; i < requiredExtension && canShiftRight && i < pages .length ; ++i ) {
151+ canShiftRight = null == pages [pages .length - i - 1 ];
152+ }
153+ if (canShiftRight ) {
154+ System .arraycopy (pages , 0 , pages , requiredExtension , pages .length - requiredExtension );
155+ } else {
156+ double [][] newPages = new double [pages .length + aligned (requiredExtension )][];
157+ System .arraycopy (pages , 0 , newPages , requiredExtension , pages .length );
158+ this .pages = newPages ;
159+ }
160+ Arrays .fill (pages , 0 , requiredExtension , null );
161+ this .minPageIndex = pageIndex ;
157162 }
158- Arrays .fill (pages , 0 , requiredExtension , null );
159- this .minPageIndex = pageIndex ;
160163 }
161164
162165 private void extendTo (int pageIndex ) {
163- this .pages = Arrays .copyOf (pages , pages . length + aligned (pageIndex - minPageIndex + 1 ));
166+ this .pages = Arrays .copyOf (pages , aligned (pageIndex - minPageIndex + 2 ));
164167 }
165168
166169 @ Override
0 commit comments