private static < T > Iterator < T > consumingForArray ( final T ... elements ) { return new UnmodifiableIterator < T > ( ) { int index = 0 ; @ Override public boolean hasNext ( ) { return index < elements . length ; } @ Override public T next ( ) { if ( ! hasNext ( ) ) { throw new NoSuchElementException ( ) ; } T result = elements [ index ] ; elements [ index ] = null ; index ++ ; return result ; } } ; }
Returns an Iterator that walks the specified array nulling out elements behind it . This can avoid memory leaks when an element is no longer necessary .