2012-12-31 64 views
1

我试图遍历一组顶点。顶点是我创建的一个自定义类。这里是我试图通过顶点迭代:Java Jung不兼容类型铸造

bCentral2 = new BetweennessCentrality<MyVertex, MyEdge>(g2); 

for(MyVertex v : g2.getVertices()) 
{ 
    v.setCentrality(bCentral2.getVertexScore(v)); 
} 

我得到的错误是从线路:MyVertex v : g2.getVertices()和消息是:

incompatible types 
    required: graphvisualization.MyVertex 
    found: java.lang.Object 

所以,我试图铸造一个ArraryList<MyVertex>和我此错误消息:

Exception in thread "main" java.lang.ClassCastException: java.util.Collections$UnmodifiableCollection cannot be cast to java.util.ArrayList 
  1. 如何我通过组顶点的迭代?
  2. 的最终目标是建立每个顶点

以下是我对MyVertex类代码的中心:

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

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

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

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

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

能否请你告诉你如何实例化'g2'?看起来你没有正确使用泛型,'getVertices()'返回'Collection '这就是为什么'for'循环无法工作的原因。 –

回答

1

我猜g2.getVertices()返回一个集合。因此您可以在Collection转换为ArrayList为:

ArrayList<MyVertex> ll = new ArrayList<>(g2.getVertices()) 

这里是documentation

+0

这是行不通的。他的'for'循环首先失败的原因是因为他收到的'不兼容类型'错误所指出的'Collection '。 –