2013-04-30 47 views
0

为了减少代码重复返回通用类型的ArrayList我通过该方法方法是,根据它是如何被调用

public <T extends Vertex<?> > ArrayList<T> getVerticebyType() { 

     ArrayList<T> array = new ArrayList<T>(); 

     for (Vertex<?> vertex : this.getAllVertice()) { 
      if (vertex instanceof Vertex<?>) 
       array.add((T) vertex); 

    } 
     return array; 

} 

替换此代码

ArrayList<Vertex> allVertice = new ArrayList<>(hypergraph.getVertices()); 

    System.out.println(allVertice.size()); 
    //hypergraph.getVerticebyType(); 
    ArrayList<ImageVertex> allImVetice = new ArrayList<>(); 
    ArrayList<TagVertex> allTagVetice = new ArrayList<>(); 

    ArrayList<LocationVertex> allLocVetice = new ArrayList<>(); 

    for (Vertex vertex : allVertice) { 
     if (vertex instanceof ImageVertex) 

      allImVetice.add((ImageVertex)vertex); 

     else if (vertex instanceof TagVertex) 

      allTagVetice.add((TagVertex)vertex); 

     else if (vertex instanceof LocationVertex) 

      allLocVetice.add((LocationVertex)vertex); 
    } 

但是当我测试这个指令

ArrayList<ImageVertex>=hyperGraph.getVerticebyType();

它返回所有顶点不管它们的类型!

有什么问题,以及如何解决它?

+0

这只是一种猜测,因为我不熟悉Java泛型,但是我希望的'如果(顶点的instanceof T)'味道 – 2013-04-30 15:52:13

回答

0

改变这一行: vertex instanceof Vertex<?>(即测试,如果顶点是顶点)到这一点: vertex instanceof T(这一项检查,如果顶点是T型的)

也确保你熟悉Oracle和教程仿制药的限制:Oracle Generics Tutorial

+3

我 我得到这个错误之前试过'无法执行的东西instanceof检查类型参数T.使用其删除顶点而不是,因为进一步的通用类型信息将被删除在运行时“ – nawara 2013-04-30 15:53:12

+0

然后尝试以下(来自:http://stackoverflow.com/questions/5734720/java-generics-obj- instanceof-t): '类别类型; if(type.isInstance(obj)){ // ... }' – jderda 2013-04-30 15:56:49

+0

这意味着我应该为每种类型创建一个泛型类! 这是不寻常的 – nawara 2013-04-30 16:43:53

1

字面相当于将中(假设T本身不是泛型类型)传递一个Class<T>和使用Class.cast(可能与Class.isInstance)。但是,使用instanceof表示您做错了;反射,更是如此。

相关问题