我試圖通過一個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