2017-02-21 177 views
0

的Java的ArrayList中的addAll我有一个Java类与泛型类型

public class PointCloud<T extends Point> 
{ 
    protected ArrayList<T > points = null; 

    public ArrayList<T> getPoints() 
    { 
     return points; 
    } 

    public void addPoints(ArrayList<T> arrayList) 
    { 
     this.points.addAll(arrayList); 
    } 

    public static PointCloud<? extends Point> combine(ArrayList<PointCloud<? extends Point>> pcList) 
    { 
     PointCloud<? extends Point> combinated_pc = new PointCloud<>(); 

     for(PointCloud<? extends Point> pc: pcList) 
     { 
      combinated_pc.addPoints(pc.getPoints()); 
     } 

     return combinated_pc; 
    } 
} 

我的Java错误是:

PointCloud<capture#8-of ? extends Point>的 类型的方法addPoints(ArrayList < capture#8-of ? extends Point>)不适用于 参数(ArrayList < capture#9-of ? extends Point>

回答

0

在这里你必须指定正确的泛型类型请使用addPoints方法。

更改您的结合了以下..

public static <P extends Point> PointCloud<P> combine(ArrayList<PointCloud<P>> pcList) { 
    PointCloud<P> combinated_pc = new PointCloud<>(); 
    for(PointCloud<P> pc: pcList) { 
     combinated_pc.addPoints(pc.getPoints()); 
    } 
    return combinated_pc; 
} 

如果你有兴趣在结合不同类型的对象,你必须修改addPoints方法。

+0

感谢您的回答,这里的问题是该方法是静态的,因此T是不可能的。 – Morkhitu

+0

@Morkhitu实际上你不明白。泛型类型T是应用的,因为它是静态的。仔细看看,T不是返回类型。返回类型是'PointCloud '。你需要学习如何在静态方法上使用泛型。 –

+0

@Morkhitu我编辑了我的答案,以解决您在课堂定义中使用的T的误解。 –