-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRandomBag.java
More file actions
38 lines (37 loc) · 784 Bytes
/
RandomBag.java
File metadata and controls
38 lines (37 loc) · 784 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import java.util.Iterator;
public class RandomBag<T> implements Iterable<T>{
private int size;
private T[] data = (T[]) new Object[2];
private void doubleArray(){
T[] newData = (T[]) new Object[data.length * 2];
for(int i = 0 ; i < size; ++i){
newData[i] = data[i];
}
data = newData;
}
public boolean isEmpty(){
return size == 0;
}
public int size(){
return size;
}
void add(T item){
if(size == data.length) doubleArray();
data[size++] = item;
}
public Iterator<T> iterator() {
return new RBIterator();
}
private class RBIterator implements Iterator<T>{
private int curId;
RBIterator(){
Algorithms.shuffleArray(data, 0, size);
}
public boolean hasNext() {
return curId < size;
}
public T next() {
return data[curId++];
}
}
}