01: /*
02: (c) Copyright 2003, 2004, 2005, 2006, 2007, 2008 Hewlett-Packard Development Company, LP
03: [See end of file]
04: $Id: RandomOrderIterator.java,v 1.6 2008/01/02 12:07:35 andy_seaborne Exp $
05: */
06:
07: package com.hp.hpl.jena.util.iterator;
08:
09: import java.util.*;
10:
11: /**
12: *
13: * RandomOrderIterator - Reorders the elements returned by an Iterator.
14: *
15: * @author jjc
16: *
17: */
18: public class RandomOrderIterator extends WrappedIterator {
19: private Random rnd = new Random();
20: private Object buffer[];
21: // one more than the index of the last non-null element.
22: int top;
23:
24: /**
25: * Wrap the base iterator, randomizing with a buffer of length sz.
26: */
27: public RandomOrderIterator(int sz, Iterator base) {
28: super (base);
29: buffer = new Object[sz];
30: top = 0;
31: fill();
32: }
33:
34: public boolean hasNext() {
35: return top > 0;
36: }
37:
38: public Object next() {
39: int ix = rnd.nextInt(top);
40: Object rslt = buffer[ix];
41: top--;
42: buffer[ix] = buffer[top];
43: fill();
44: return rslt;
45: }
46:
47: public void remove() {
48: throw new UnsupportedOperationException(
49: "randomizing does not allow modification");
50: }
51:
52: private void fill() {
53: while (top < buffer.length && super .hasNext()) {
54: buffer[top++] = super .next();
55: }
56: }
57:
58: }
59: /*
60: (c) Copyright 2003, 2004, 2005, 2006, 2007, 2008 Hewlett-Packard Development Company, LP
61: All rights reserved.
62:
63: Redistribution and use in source and binary forms, with or without
64: modification, are permitted provided that the following conditions
65: are met:
66:
67: 1. Redistributions of source code must retain the above copyright
68: notice, this list of conditions and the following disclaimer.
69:
70: 2. Redistributions in binary form must reproduce the above copyright
71: notice, this list of conditions and the following disclaimer in the
72: documentation and/or other materials provided with the distribution.
73:
74: 3. The name of the author may not be used to endorse or promote products
75: derived from this software without specific prior written permission.
76:
77: THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
78: IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
79: OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
80: IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
81: INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
82: NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
83: DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
84: THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
85: (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
86: THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
87: */
|