簡體   English   中英

通配符,Java中的通用

[英]wildcard, generic in java

我在countList方法上收到編譯時錯誤。

public static void countList( List<? extends Number> list, int count ){
        for( int i = 0; i < count; i++ ){
            list.set(i, i-1);
        }
}

public static void clearList( List<?extends Number> list){
    list.clear();
}

它說:類型List中的方法set(int,capture#2-of?擴展Number)不適用於參數(int,int)

此錯誤消息是什么意思? 為什么不能設置列表中的元素? 為什么可以清除列表?

因為它是“擴展數字的東西,但我不知道是什么”的列表。 您不能只將整數放在其中,如果實際上是一個雙精度列表怎么辦?

List<Double> list = new ArrayList<Double>();
list.add(Double.valueOf(4.5);
countList(list, 1);
Double d = list.get(0); //what happens here?  You put an Integer in there!  class cast exception

您可以清除列表,因為對於該操作,實際位於其中的Number的哪個子類型都沒有關系。 清除是清除。

問題在於,由於類型擦除,編譯器在運行時不知道將哪種類型的Number添加到列表中。 考慮以下示例:

public static void main(String[] args) {
        List<Integer> intList= new ArrayList<Integer>();
        // add some Integers to the list here
        countList(intList, 4);

}

public static void countList( List<? extends Number> list, int count ) {
        for( double d = 0.0; d < count; d++ ){
            list.set((int)d, d-1); // problem at d-1, because at runtime, 
            // the double result of d-1 will be autoboxed to a Double, 
            // and now you have added a Double to an Integer List (yikes!);
        }
}

因此,您永遠無法使用? extends SomeObject 添加到通用類型的Collection中? extends SomeObject ? extends SomeObject語法。 如果必須添加,則可以將方法聲明更改為:

  1. 將方法聲明更改為public static void countList( List<Number> list, int count )
  2. 將方法更改為public static void countList( List<? super Integer> list, int count )

無論哪種方式,編譯器都將停止抱怨,因為它可以放心,您絕不會在列表中添加與聲明的列表類型不同的任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM