[英]How to use Strings for .get() and .put() with TreeMap in Java
我目前正在为使用String值作为顶点的无向加权图创建Prim的最小生成树。 我的老师说,要创建图形,我们可以使用课本中的edge和graph类。 但是,本书使用Integers作为顶点而不是字符串。 我尝试将所有Integer替换为Strings,但是由于从通用TreeMap中使用.get()的每一行都收到了编译器错误,因为它找不到符号方法get(java.lang.String)。 经过一些工作,我发现初始化TreeMap并使用.add()可用于字符串,但不能用于.get()或.put()方法。 此处的代码与书中的代码完全相同,只是将Integer替换为String。
如何使.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);
}
}
您的问题不在于TreeMap
。 TreeMap
是基于密钥的集合。 您的adjList
'面临问题。 Vector是基于索引的集合,您只能获得带有其索引的项目。
尝试如下更改方法
public String getEdgeWeight(int v, String w) {
return adjList.get(v).get(w);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.