【发布时间】:2021-12-25 02:26:22
【问题描述】:
对于我的班级,我必须创建一个迭代器,它将生成一个 LinkedSet 的幂集。根据我的教授,我必须遍历 int 电流的 bitString。其中 current 是我们要添加主集合元素的子集。我一直有 NullPointerException。我想我正确地循环了 bitString 但是当我想移动到集合中的下一个节点时,它说它是空的。我已经盯着这个看了 12 个小时,不知道该怎么做。我的教授提供了一个框架,所以我会解释什么是我的,什么是他的。
这是框架:
private class LinkedSetPowerSetIterator implements Iterator<Set<T>> {
// cardinality of this set
int N;
// cardinality of the power set (2^N)
int M;
// the integer identifier of the current subset, i.e. the current element
// of the power set. Legal values range from 0..M-1 inclusive.
int current;
public LinkedSetPowerSetIteratorInt32BitString() {
// initialize N, M, and current here
}
public boolean hasNext() {
return current < M;
}
public Set<T> next() {
LinkedSet<T> s = new LinkedSet<T>();
char[] bitstring = Integer.toBinaryString(current).toCharArray();
// iterate from right to left over bitstring and the internal
// linked list to ensure that the call to add will insert a new
// first node (constant time)
current = current + 1;
return s;
}
public void remove() {
}
}
到目前为止我所拥有的:
private class myPowerIterator implements Iterator<Set<T>> {
// cardinality of set
int N;
// cardinality of power set (2^N)
int M;
//current subset in power set
int current;
// starting node, rear node
Node set = rear;
public myPowerIterator() {
N = size;
M = (int)Math.pow(2, N);
current = 0;
}
public boolean hasNext() {
return (current < M);
}
public Set<T> next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
LinkedSet<T> result = new LinkedSet<T>();
char[] bitString = Integer.toBinaryString(current).toCharArray();
for (int i = bitString.length - 1; i >= 0; i--) {
if (bitString[i] == 1) {
result.add(set.element); // How do I make sure it is adding elements
set = set.prev; // from starting set? Keep getting Error:
} // NullPointerException: Cannot read field
else { // "prev" because this.set is null.
set = set.prev;
}
}
current = current + 1;
return result;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
【问题讨论】:
-
你的
LinkedSet<T>实现Iterable<T>了吗? -
我只允许实现Iterator接口
-
如何按顺序检索
LiknedSet的元素?如果不注明,PowerSetIterator就无法实现。 -
这是个好问题,我不知道答案
标签: java iterator set powerset