0

現在、頂点に文字列値を使用する無向加重グラフ用のプリムの最小スパニング ツリーの作成に取り組んでいます。グラフを作成するには、教科書のエッジ クラスとグラフ クラスを使用できると先生は言いました。ただし、この本では、文字列ではなく頂点に整数を使用しています。すべての整数を文字列に置き換えようとしましたが、シンボル メソッド get(java.lang.String) が見つからなかったため、ジェネリック TreeMap から .get() を使用するすべての行でコンパイラ エラーが発生しました。ちょっとした作業の後、TreeMap の初期化と .add() の使用は文字列では機能するが、.get() または .put() メソッドでは機能しないことがわかりました。これは、整数が文字列に置き換えられていることを除いて、本とまったく同じコードです。

.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);
    }
}
4

1 に答える 1

0

あなたの問題はにありませんTreeMapTreeMapキーベースのコレクションです。ベクター ' adjList' で問題が発生しています。Vectorは Indexed ベースのコレクションで、インデックスのみで項目を取得できます。

以下のようにメソッドを変更してみてください

public String getEdgeWeight(int v, String w) {
    return adjList.get(v).get(w);
}
于 2013-03-13T01:21:31.467 に答える