如何在Java中将.get()和.put()的字符串与TreeMap一起使用
我目前正在为一个无向加权图创建一个Prim最小生成树,该图使用字符串值作为顶点。为了创建图形,我的老师说我们可以使用课本上的edge和graph课程。但是,本书对顶点使用整数而不是字符串。我尝试用字符串替换所有整数,但对于使用通用树映射中的.get()的每一行,我都收到一个编译器错误,因为它找不到符号方法get(java.lang.String)。在做了一些工作之后,我发现初始化树映射并使用.add()可以处理字符串,但不能处理.get()或.put()方法。这里的代码与书中的代码完全相同,只是整数被替换为字符串 如何使.get()和.put()方法处理字符串如何在Java中将.get()和.put()的字符串与TreeMap一起使用,java,string,graph,treemap,Java,String,Graph,Treemap,我目前正在为一个无向加权图创建一个Prim最小生成树,该图使用字符串值作为顶点。为了创建图形,我的老师说我们可以使用课本上的edge和graph课程。但是,本书对顶点使用整数而不是字符串。我尝试用字符串替换所有整数,但对于使用通用树映射中的.get()的每一行,我都收到一个编译器错误,因为它找不到符号方法get(java.lang.String)。在做了一些工作之后,我发现初始化树映射并使用.add()可以处理字符串,但不能处理.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);
}
}
import java.util.*;
类图{
private int numVertices;//图中的顶点数
private int numEdges;//图中的边数
私有向量表;
//建造师
公共图(int n){
数值=n;
numEdges=0;
adjList=新向量();
对于(int i=0;i您的问题不在于TreeMap
TreeMap
是基于键的集合。您是
向量“adjList
”面临问题。是一个基于索引的集合
您只能获取带有索引的项
尝试如下更改您的方法
public String getEdgeWeight(int v, String w) {
return adjList.get(v).get(w);
}