如何在Java中使用带有TreeMap的.get()和.put()字符串

时间:2013-03-13 01:13:38

标签: java string graph treemap

我目前正致力于为无向的加权图创建Prim的最小生成树,该图使用顶点的字符串值。为了创建图形,我的老师说我们可以使用教科书中的边缘和图形类。但是,本书使用Integers作为顶点而不是字符串。我尝试用字符串替换所有Integers,但是我从通用TreeMap使用.get()的每一行都收到编译器错误,因为它找不到符号方法get(java.lang.String)。经过一番工作,我发现初始化TreeMap并使用.add()可以使用Strings,但不能使用.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);
    }
}

1 个答案:

答案 0 :(得分:0)

问题不在于TreeMapTreeMap是基于密钥的集合。你是 面对Vector'adjList'的问题。 Vector是基于索引的集合 你只能得到一个带有索引的项目。

尝试按以下方式更改您的方法

public String getEdgeWeight(int v, String w) {
    return adjList.get(v).get(w);
}