Cod*_*lus 9 java casting treemap comparable sortedmap
我正在使用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)
Run Code Online (Sandbox Code Playgroud)
以下是与错误相关的代码:
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**
}
Run Code Online (Sandbox Code Playgroud)
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
}
}
Run Code Online (Sandbox Code Playgroud)
Rah*_*hul 16
如何将MyVertex类型转换为可比较的?
实现Comparable接口.
public class MyVertex implements Comparable<MyVertex> {
@Override
public int compareTo(Object o) {
// comparison logic goes here
}
}
Run Code Online (Sandbox Code Playgroud)
或者,您可以将a传递comparator给.的构造函数TreeMap.
new TreeMap<MyVertex, Double>(new Comparator<MyVertex>()
{
public int compare(MyVertex o1, MyVertex o2)
{
//comparison logic goes here
}
});
Run Code Online (Sandbox Code Playgroud)
为什么这有必要?
因为您存储在树形图中,它是一个有序地图(按键排序).地图键需要具有可比性,以确保地图中的排序顺序.
MyVertexclass应该实现Comparable为树映射使用compareTo方法根据键对映射进行排序.
public class MyVertex implements Comparable<MyVertex> {
@Override
public int compareTo(MyVertex o) {
// do the comparison logic
}
}
Run Code Online (Sandbox Code Playgroud)
其他选项是将比较器对象传递给TreeMap http://docs.oracle.com/javase/1.5.0/docs/api/java/util/TreeMap.html#TreeMap(java.util.Comparator)
| 归档时间: |
|
| 查看次数: |
25007 次 |
| 最近记录: |