0
我目前正在爲使用頂點字符串值的無向,加權圖創建Prim的最小生成樹。爲了創建圖形,我的老師說我們可以使用教科書中的邊和圖表類。然而,本書使用整數來表示頂點而不是字符串。我嘗試用字符串替換所有整數,但是我收到每個使用來自通用TreeMap的.get()的行的編譯器錯誤,因爲它無法找到符號方法get(java.lang.String)。經過一些工作,我發現初始化TreeMap並使用.add()可以與字符串一起使用,但不能使用.get()或.put()方法。這裏的代碼與本書中的方式完全相同,只是Integer被替換爲String。如何在Java中使用字符串for .get()和.put()與TreeMap
如何使.get()和.put()方法與字符串一起使用?
import java.util.*;
class Graph {
private int numVertices; //number of vertices in the graph
private int numEdges; //number of edges in the graph
private Vector<TreeMap<String, String>> adjList;
//constructor
public Graph(int n) {
numVertices=n;
numEdges=0;
adjList=new Vector<TreeMap<String, String>>();
for(int i=0;i<numVertices;i++) {
adjList.add(new TreeMap<String, String>());
}
}
//Determines the number of vertices in the graph
public int getNumVertices() {
return numVertices;
}
//Determines the number of edges in the graph
public int getNumEdges() {
return numEdges;
}
//Determines the weight of the edge between vertices v and w
public String getEdgeWeight(String v, String w) {
return adjList.get(v).get(w);
}
//Add the edge to both v's and w's adjacency list
public void addEdge(String v, String w, int wgt) {
adjList.get(v).put(w,wgt);
adjList.get(w).put(v,wgt);
numEdges++;
}
//Adds an edge to the graph
public void addEdge(Edge e) {
//Extract the vertices and weight from the edge e
String v=e.getV();
String w=e.getW();
int weight=e.getWeight();
addEdge(v, w, weight);
}
//Finds the edge connecting v and w
public Edge findEdge(String v,String w) {
int wgt=adjList.get(v).get(w);
return new Edge(v, w, wgt);
}
//package access
//Returns the adjacency list for given vertex
TreeMap<String, String> getAdjList(String v) {
return adjList.get(v);
}
}