要编写一个用于Java哈希表节点的迭代器,可以使用Java的Iterator接口来实现。下面是一个示例代码:
import java.util.Iterator;
public class HashTableIterator implements Iterator> {
private Node[] table; // 哈希表的数组
private int index; // 当前遍历到的索引
private Node current; // 当前节点
public HashTableIterator(Node[] table) {
this.table = table;
this.index = 0;
this.current = null;
}
@Override
public boolean hasNext() {
// 如果当前节点不为空,直接返回true
if (current != null) {
return true;
}
// 遍历哈希表数组,找到下一个不为空的节点
while (index < table.length && table[index] == null) {
index++;
}
// 如果找到了不为空的节点,将其赋值给current,并返回true
if (index < table.length) {
current = table[index];
return true;
}
// 否则,返回false
return false;
}
@Override
public Node next() {
// 获取当前节点
Node node = current;
// 将当前节点置为其下一个节点
current = current.getNext();
// 如果当前节点为空,说明已经遍历到当前链表的末尾,将index加1,以遍历下一个链表
if (current == null) {
index++;
}
// 返回当前节点
return node;
}
}
上述代码中,HashTableIterator类实现了Iterator接口,并使用泛型来支持不同类型的键和值。该迭代器使用一个哈希表的数组table,一个索引index和一个当前节点current来追踪当前遍历的位置。
在hasNext方法中,首先判断当前节点current是否为空,如果不为空,则说明还有剩余的节点,直接返回true。如果current为空,则通过遍历哈希表数组,找到下一个不为空的节点,并将其赋值给current。如果找到了下一个节点,则返回true,否则返回false。
在next方法中,首先获取当前节点current,然后将current置为其下一个节点current.getNext()。如果current为空,说明已经遍历到当前链表的末尾,将index加1,以遍历下一个链表。最后,返回当前节点。
使用该迭代器,可以通过以下方式遍历哈希表中的节点:
HashTableIterator iterator = new HashTableIterator<>(table);
while (iterator.hasNext()) {
Node node = iterator.next();
// 处理节点
}
其中,table是一个Node类型的哈希表数组,Node是表示哈希表节点的类。可以根据实际情况进行调整。