我正在尝试编写一个实现Enumeration>的类,以便根据我想要的获取的不是Collection,而是Set或List...。
我希望能够使用以下语法:
Enumeration<Set<Integer>> setEn =
new CollectionEnumeration<Integer, Set<Integer>>(ids, HashSet.class);
或:
Enumeration<Set<Integer>> setEn =
new CollectionEnumeration<Integer, Set>(ids, HashSet.class);
或:
Enumeration<List<Integer>> listEn =
new CollectionEnumeration<Integer, List<Integer>>(ids, ArrayList.class);
或:
Enumeration<List<Integer>> listEn =
new CollectionEnumeration<Integer, List>(ids, LinkedList.class);
声明类的正确方法是什么?
这是我到目前为止所拥有的:
class CollectionEnumeration<T, Coll extends Collection<T>> implements Enumeration<Coll> {
final private List<List<T>> stopListZoneIds;
final private Class<? extends Coll> klass;
final private int[] index;
final private int max;
private int current;
private int stopIndex;
CollectionEnumeration(List<List<T>> stopListZoneIds, Class<? extends Coll> klass) {
this.stopListZoneIds = stopListZoneIds;
this.klass = klass;
int all = 1;
index = new int[stopListZoneIds.size()];
for (int stopIdx = 0; stopIdx < stopListZoneIds.size(); stopIdx++) {
index[stopIdx] = 0;
all *= stopListZoneIds.get(stopIdx).size();
}
max = all;
current = 0;
stopIndex = 0;
}
@Override
public boolean hasMoreElements() {
return current < max;
}
@Override
public Coll nextElement() {
if (!hasMoreElements()) {
return null;
}
try {
Coll collection = klass.newInstance();
for (int stopIdx = 0; stopIdx < stopListZoneIds.size(); stopIdx++) {
collection.add(stopListZoneIds.get(stopIdx).get(index[stopIdx]));
}
doStep();
return collection;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private void doStep() {
if (current >= max) {
throw new RuntimeException("Shouldn't call doStep() when !hasMoreElements()");
}
do {
if (index[stopIndex] < stopListZoneIds.get(stopIndex).size()) {
index[stopIndex]++;
current++;
return;
} else {
index[stopIndex] = 0;
stopIndex++;
}
} while(stopIndex < stopListZoneIds.size());
current++;
}
}