2 * Copyright (c) 2007 Yahoo! Inc. All rights reserved.
3 * See accompanying LICENSE file.
5 package com
.yahoo
.pig
.impl
.util
;
7 import java
.io
.IOException
;
10 public class RewindableIterator
<E
> {
11 private Iterator
<E
> it
;
12 private ArrayList
<E
> buf
;
14 boolean noRewind
= false;
16 public RewindableIterator(Iterator
<E
> it
) {
18 buf
= new ArrayList
<E
>();
21 public boolean hasNext() {
22 return (buf
.size() > pos
|| it
.hasNext());
25 public boolean hasNext(int k
) {
26 int need
= k
- (buf
.size() - pos
);
40 public void rewind() throws IOException
{
41 if (noRewind
) throw new IOException("Internal error: attempt to rewind RewindableIterator after rewind has been disabled.");
45 public void noRewind() {
48 // clear out part of buffer that has been read
57 if (buf
.size() <= pos
) return it
.next();
58 else return buf
.remove(pos
);
60 if (buf
.size() <= pos
) buf
.add(it
.next());
62 return buf
.get(pos
++);