1 6 7 package com.hp.hpl.jena.util.iterator; 8 9 import java.util.*; 10 17 public class RandomOrderIterator extends WrappedIterator { 18 private Random rnd = new Random(); 19 private Object buffer[]; 20 int top; 22 25 public RandomOrderIterator(int sz, Iterator base) { 26 super(base); 27 buffer = new Object [sz]; 28 top = 0; 29 fill(); 30 } 31 32 public boolean hasNext() { 33 return top > 0; 34 } 35 public Object next() { 36 int ix = rnd.nextInt(top); 37 Object rslt = buffer[ix]; 38 top--; 39 buffer[ix] = buffer[top]; 40 fill(); 41 return rslt; 42 } 43 44 public void remove() { 45 throw new UnsupportedOperationException ("randomizing does not allow modification"); 46 } 47 48 private void fill() { 49 while ( top < buffer.length && super.hasNext() ) { 50 buffer[top++] = super.next(); 51 } 52 } 53 54 } 55 | Popular Tags |