我试图通过一个HashMap迭代包含有向边的ArrayList,对于Edgeweighted向图。我遵循了类似问题的说明,但无法正常工作。迭代通过定向的ArrayList的边缘HashMap中,提取有向边数据
我想: 迭代通过HashMap中,检索每个ArrayList中。 然后迭代ArrayList中的directedEdges。 打印出来的有向边,它具有以下toString方法:
public String toString(){
return String.format("%s->%s %d", v, w, weight);
}
低于满EdgeDirectedGraph类,toString方法我查询是在底部。
import java.util.*;
import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class EdgeWeightedDiGraph{
private static final String NEWLINE = System.getProperty("line.separator");
private int V;
private int E;
private HashMap<String, ArrayList<DirectedEdge>> adjacencyList;
public EdgeWeightedDiGraph(String filename, String delim){
BufferedReader br = null;
try{
br = new BufferedReader(new FileReader(filename));
E = 0;
V = Integer.parseInt(br.readLine());
//System.out.println(V);
String line = null;
this.adjacencyList = new HashMap<String, ArrayList<DirectedEdge>>();
while ((line = br.readLine()) != null) {
//adj = (Bag<Integer>[]) new Bag[V];
String arr[] = line.split(delim); // properties
String v = arr[0];
String w = arr[1];
int e = Integer.parseInt(arr[2]);
DirectedEdge dEdge = new DirectedEdge(v, w, e);
addEdge(dEdge);
System.out.println(dEdge.from()+dEdge.to()+dEdge.weight());
}
}
catch (FileNotFoundException ex) {
System.out.println("Error: File not found");
Logger.getLogger(EdgeWeightedDiGraph.class.getName()).log(Level.SEVERE, null, ex);
}
catch (IOException ex) {
Logger.getLogger(EdgeWeightedDiGraph.class.getName()).log(Level.SEVERE, null, ex);
}
finally{
try {
br.close();
}
catch (IOException ex) {
Logger.getLogger(EdgeWeightedDiGraph.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
public HashMap getMap(){
return adjacencyList;
}
public int V(){
return V;
}
public int E(){
return E;
}
public void addEdge(DirectedEdge e)
{
String v = e.from();
String w = e.to();
ArrayList<DirectedEdge> item = new ArrayList<DirectedEdge>();
item.add(e);
adjacencyList.put(v, item);
System.out.println(v+item);
E++;
}
public Iterable<DirectedEdge> adjacencyList(String v){
return adjacencyList.get(v);
}
public Iterable<DirectedEdge> edges()
{
public String toString() {
StringBuilder s = new StringBuilder();
s.append(V + " " + E + NEWLINE);
for (HashMap.Entry<String, ArrayList<DirectedEdge>> entry : adjacencyList.entrySet()){
ArrayList<DirectedEdge> arrList = entry.getValue();
for(DirectedEdge e : arrList){
s.append(e + " "); }
s.append(NEWLINE);
}
return s.toString();
}
}
下面是输出: 我可以看到,有向边被添加到该图中,但只有一半在toString()方法打印出来。
Print out of edges being added
A[A->B 5]
AB5,
B[B->C 4]
BC4,
C[C->D 8]
CD8,
D[D->C 8]
DC8,
D[D->E 6]
DE6 ,
A[A->D 5]
AD5,
C[C->E 2]
CE2,
E[E->B 3]
EB3,
A[A->E 7]
AE7
“的toString()输出:A->电子7 B->的C 4 C-> e 2的D->电子6 E-> B 3”
对不起,我在格式化时遇到了问题,同时尝试添加剩余的输出,然后就搞砸了,现在我显然无法编辑90分钟了? – jewfro
试图从的toString()添加输出: A->电子7 B->的C 4 C-> e 2的 D->电子6 E->乙3 – jewfro
可以请标记备份如我拼命地试图修复它,因为你标记我失望,我不断收到关于代码的错误消息,试图在上面的评论中包括结果,所以我正在移动东西 – jewfro