我正在为我的链式哈希表构建一个键的内部类和值迭代器。我遇到了麻烦。我首先检查了一个HashTable条目,然后迭代它指向的链表。至于我对这个关键迭代器的跟踪,逻辑应该是正确的。这是它的样子:
import java.util.Iterator;
public class Demos {
public static void main(String[] args) {
HashDict dictionary = new HashDict();
dictionary.add("hello", 13);
System.out.println("after first add: " + dictionary.toString());
dictionary.displayTable();
System.out.println("after second add: " + dictionary.add("hi", 12));
dictionary.displayTable();
}
}
然而,在我写的测试程序中,
after first add: 13
null, null
after second add: 12
null, null
null, null
我得到了这样的结果
public void displayTable() {
Iterator traverse = getKeyIterator();
Iterator traverseValues = getValueIterator();
while (traverse.hasNext()) {
System.out.print(traverse.next());
System.out.print(", " + traverseValues.next());
System.out.println();
}
}
displayTable只是HashTable类中用于测试迭代器方法的方法。它看起来像这样:
private class KeyIterator implements Iterator<K> {
private int currentIndex; // Current position in hash table
private int numberLeft; // Number of entries left in iteration
private KeyIterator() {
currentIndex = 0;
numberLeft = numberOfEntries;
} // end default constructor
public boolean hasNext() {
return numberLeft > 0;
} // end hasNext
public K next() {
K result = null;
if (hasNext()) {
LList<TableEntry> items = hashTable[currentIndex];
Iterator<TableEntry> traverse = items.getIterator();
while (traverse.hasNext()) {
TableEntry<K, V> item = new TableEntry();
item = traverse.next();
result = item.key;
numberLeft--;
}
currentIndex++;
} else {
throw new NoSuchElementException();
}
return result;
} // end next
public void remove() {
throw new UnsupportedOperationException();
} // end remove
} // end KeyIterator
为什么这个keyIterator方法会像这样工作?任何帮助都会非常感激!
~~~~~~~~~~~~~
更新Key Iterator的版本:
Exception in thread "main" java.lang.NullPointerException
at HashDict$KeyIterator.next(HashDict.java:48)
at Demos.main(Demos.java:40)
现在我的错误是这样的:
() => {
// upload success
if (uploadTask.snapshot.downloadURL) {
upload.url = uploadTask.snapshot.downloadURL; //this is the variable
upload.name = upload.file.name;
this.fire.collection(`users/${this.auth.userId}/projects`).add( {
photoURL: upload.url, file: upload.file.name, })
this.saveFileData(upload);
this.getZipFileContent(upload.url, path);
return;
} else {
console.error('No download URL!');
}
答案 0 :(得分:0)
首先,你的密钥迭代器增加numberOfEntries
是没有意义的。由于该变量不是KeyIterator
类的实例变量,因此我假设它是封闭类的实例变量。只应在向哈希表添加或删除元素时修改它。
另一个问题是currentIndex
不足以跟踪当前密钥的位置。您需要hashTable
中当前条目的索引+当前条目的链接列表中的当前链接。这将允许您在固定时间内迭代到该链表中的下一个链接。