【发布时间】:2012-03-23 15:44:31
【问题描述】:
采用 java 类,我们必须设计自己的 HashSet 类。 (不使用 JAVA api)
我必须为此实现和迭代器,我对使用一个的语义感到困惑。
不确定是否应该允许调用 Next() 来移动迭代器的索引,或者用户是否必须绝对使用 next() 和 hasNext() 循环来移动索引.
例如,如果用户在没有 hasNext() 的情况下连续多次调用 next() 会发生什么?
感谢大家的帮助!
public class HashWordSet implements WordSet {
private int size;
private Node[] buckets = new Node[8];
//above is only provided for mention of variables
private class Node {
Word value;
Node next = null;
public Node(Word word) {value = word;}
public String toString() {return value.toString();}
}
class WordIterator implements Iterator<Word> {
private Node next;
private int index = 0;
public Word next() {
Node element = next;
if (element == null)
throw new NoSuchElementException();
if ((next = element.next) == null) {
Node[] temp = buckets;
while (index < temp.length && (next = temp[index++]) == null)
;
}
return element.value;
}
public boolean hasNext() {
return (next != null);
}
【问题讨论】: