2017-02-21 182 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的誤解。 –