【发布时间】:2026-01-11 19:25:02
【问题描述】:
我正在编写一个名为 graph 的类,我用 Hashmap 表示有向图。我想创建一个通过以下方式打印出整个图表的方法:
key1: value13, valeue17, ..
key2: value21, ...
其中 value13 是 node1(key1) 指向的 node3 的值。 所以,对于像 1->2->3 和 2 也指向 4 的东西,我需要:
1: 2
2: 3,4
我的代码如下所示:
public class Graph<T>{
Map<Node<T>, List<Node<T>>> graph;
//constructors and methods
void printGraph(){
System.out.println(graph.keySet().iterator().next().value); // is printing 7
Iterator itKey = graph.keySet().iterator();
System.out.println(itKey.next()); // printing Graph$Node@15db9742
System.out.println(itKey.next().value); //error
while(itKey.hasNext()){
//code
}
public static void main(String[] args){
Graph<Integer> graph = new Graph<>();
Node<Integer> n1 = new Node<>(7);
Node<Integer> n2 = new Node<>(2);
graph.connect(n1, n2);
graph.printGraph();
}
}
我的问题出现在方法printGraph() 中,我在其中定义了一个Iterator。我想要做的是创建一个迭代器
在键集上,然后为每个键创建一个迭代器,该迭代器将打印所有值。如您所见,如果我尝试打印System.out.println(graph.keySet().iterator().next().value);
我得到一个 7,这是有道理的,因为它是我在 keySet() 中的第一个键的值。如果我用另一种方式来初始化迭代器Iterator itKey = graph.keySet().iterator();,这是一个指向Node的迭代器:
System.out.println(itKey.next()); // printing Graph$Node@15db9742
虽然,如果我尝试打印它的值:
System.out.println(itKey.next().value); //error
我收到以下错误:
error: cannot find symbol
System.out.println(itKey.next().value);
^
symbol: variable value
location: class Object
1 error
这不应该是一回事吗?为什么会出现错误?
【问题讨论】:
-
这个问题归结为如何打印
Map,其中键为Node,值为List<Node<T>>? -
其实问题更多是和迭代器打交道,它被应用在这个打印问题上,但问题并不是这样
标签: java generics iterator raw-types