9

重複の可能性:
Java: SortedMap、TreeMap、Comparable? 使い方?

Java JungIグラフ パッケージと Netbeans 7 を使用しています。Java から次のエラーが発生します。

 Exception in thread "main" java.lang.ClassCastException: graphvisualization.MyVertex cannot be cast to java.lang.Comparable
    at java.util.TreeMap.put(TreeMap.java:542)

エラーに関連するコードは次のとおりです。

SortedMap<MyVertex, Double> vMap = new TreeMap<MyVertex, Double>();
       double curRank = 0;
       for(MyVertex v: g.getVertices())                 //g is a SparseGraph<MyVertex, MyEdge>
       {
           curRank = vertexRank.getVertexScore(v);
           vMap.put(v, curRank);                        //**Here is my Error**
       }

クラス MyVertex は、グラフ用に作成したクラスです。以下は MyVertex のコードです

public class MyVertex 
{
    int vID;                    //id for this vertex
    double centrality;          //centrality measure for this vertex
    int degree;                 //the degree of this vertex

    public MyVertex(int id)
    {
        this.vID = id;
        this.centrality=0;
        this.degree=0;
    }

    public double getCentrality()
    {
        return this.centrality;
    }

    public void setCentrality(double centrality)
    {
        this.centrality = centrality;
    }

    public int getDegree()
    {
        return this.degree;
    }

    public void setDegree(int deg)
    {
        this.degree = deg;
    }

    public void incrementDegree()
    {
        this.degree++;
    }

    public void decrementDegree()
    {
        this.degree--;
    }

    @Override
    public String toString()
    {
        return "v"+vID;
    }

    int compareTo(MyVertex v) 
    {
        return (this.degree < v.degree) ? 1 : 0;          //this will do descendingly
    }
}
  1. MyVertex 型を Comparables にキャストするにはどうすればよいですか?
  2. なぜこれが必要なのですか?(理由はすぐにはわかりません)
4

5 に答える 5

0

-まず、クラス MyVertex に Comparable を実装させる必要があります。

例えば:

public class MyVertex implements Comparable {

  @Override
  public int compareTo(MyVertex o) {


  }
 }

-ただし、オブジェクトの複数の属性に基づいて比較する場合は、インターフェイスを使用することをお勧めしjava.util.Comparator<T>ます。

new TreeMap<MyVertex, Double>(new Comparator<MyVertex>()
        {
            public int compare(MyVertex o1, MyVertex o2)
            {

            } 
    });
于 2013-01-03T06:33:27.640 に答える