我使用广度优先搜索来遍历数组列表。现在我有一个Graph类和一个Node类。我遇到的问题是这一行:for(Node adj : n.adjacentNodes){
我认为它与此行的类型转换有关:Node n = (Node)q.poll();
编译器不喜欢这个,但为什么会这样呢?除了我的对象n是Node类型并且我试图在这个for循环中遍历它之外,我可以为编译器更改什么?
这是我的代码:
节点类:
import java.util.*;
public class Node {
public String data; // data element
public boolean visited=false; // flag to track the already visited node
public List adjacentNodes = new LinkedList(); // adjacency list
public Node rootNode;
public Node(String data){
this.data = data;
}
public void addAdjacentNode(final Node node){
adjacentNodes.add(node);
node.adjacentNodes.add(this);
adjacentNodes.add(rootNode);
node.adjacentNodes.add(this);
}
}
我的图表类:
import java.util.*;
/*- enqueue the start node to a Queue
- make the start node as visited
- while queue is not empty
- dequeue the node lets say u
- print or whatever you want to
- for every adjacent node v of u
- if v is not already visited
- mark v as visited
- enqueue v to the Queue*/
public class Graph {
public List nodes = new ArrayList();
public void breadthFirstTraversal(Node rootNode){
Queue<Node> q = new LinkedList<Node>();
// Queue q = new LinkedList();
q.add(rootNode);
printNode(rootNode);
rootNode.visited=true;
while(!q.isEmpty()){
Node n = (Node)q.poll();
System.out.print(n.data + " ");
for(Node adj : n.adjacentNodes){
if(!adj.visited){
adj.visited=true;
q.add(adj);
}
}
clearNodes();
}
}
private void clearNodes() {
// TODO Auto-generated method stub
nodes = null; //clear nodes and set to null
}
private void printNode(Node node) {
// TODO Auto-generated method stub
System.out.print(node);
}
public static void main(String[] args) {
Node frankfurt = new Node("frankfurt");
Node mannheim = new Node("mannheim");
Node wurzburg = new Node("wurzburg");
Node stuttgard = new Node("stuttgard");
Node kassel = new Node("kassel");
Node karlsruhe = new Node("karlsruhe");
Node erfurt = new Node("erfurt");
Node numberg = new Node("numberg");
Node augsburg = new Node("augsburg");
Node munchen = new Node("munchen");
Graph g = new Graph();
g.nodes.add(frankfurt);
g.nodes.add(mannheim);
g.nodes.add(wurzburg);
g.nodes.add(stuttgard);
g.nodes.add(kassel);
g.nodes.add(karlsruhe);
g.nodes.add(erfurt);
g.nodes.add(numberg);
g.nodes.add(augsburg);
g.nodes.add(munchen);
frankfurt.addAdjacentNode(mannheim);
frankfurt.addAdjacentNode(wurzburg);
frankfurt.addAdjacentNode(kassel);
mannheim.addAdjacentNode(karlsruhe);
karlsruhe.addAdjacentNode(augsburg);
augsburg.addAdjacentNode(munchen);
munchen.addAdjacentNode(kassel);
munchen.addAdjacentNode(numberg);
wurzburg.addAdjacentNode(erfurt);
wurzburg.addAdjacentNode(numberg);
numberg.addAdjacentNode(stuttgard);
g.breadthFirstTraversal(frankfurt);
}
}
答案 0 :(得分:2)
当声明你的队列时,如果你指定它将要存储的元素的'Type',那么你就不需要强制转换。 队列q = new LinkedList();
正确的方式:
Queue<Node> q = new LinkedList<Node>();
答案 1 :(得分:0)