public Iterator < int [ ] > fastPassByReferenceIterator ( ) { final int [ ] assignments = new int [ dimensions . length ] ; if ( dimensions . length > 0 ) assignments [ 0 ] = - 1 ; return new Iterator < int [ ] > ( ) { @ Override public boolean hasNext ( ) { for ( int i = 0 ; i < assignments . length ; i ++ ) { if ( assignments [ i ] < dimensions [ i ] - 1 ) return true ; } return false ; } @ Override public int [ ] next ( ) { // Add one to the first position assignments [ 0 ] ++ ; // Carry any resulting overflow all the way to the end. for ( int i = 0 ; i < assignments . length ; i ++ ) { if ( assignments [ i ] >= dimensions [ i ] ) { assignments [ i ] = 0 ; if ( i < assignments . length - 1 ) { assignments [ i + 1 ] ++ ; } } else { break ; } } return assignments ; } } ; }
This is its own function because people will inevitably attempt this optimization of not cloning the array we hand to the iterator to save on GC and it should not be default behavior . If you know what you re doing then this may be the iterator for you .