2013-04-10 77 views
1

下面代碼中的listNum.add(num)有什麼問題; (參考 - http://docs.oracle.com/javase/tutorial/java/generics/lowerBounded.html泛型Java超級

它使編譯錯誤,因爲 Add方法(捕獲#1-的?超長)在類型列表中是不適用的參數(編號)

public class GenericSuper { 

    List<? super Long> listNum = new LinkedList <Number>(); 
    List<? super ExportException> listExp= new LinkedList<RemoteException>(); 

    public List<? super ExportException> addList() 
    { 
     Number num = 10; 
     listNum.add(num); 
     RemoteException rme = new RemoteException(); 
     listExp.add(rme); 
     return rme; 
    } 
} 
+5

爲什麼不只是將'listExp'聲明爲'List ',將'listNum'聲明爲'List '?我懷疑你應該重新審視有界通配符的含義。 – 2013-04-10 11:38:37

+0

我想在listExp中存儲listNum和ExportException中的所有超類。因此,在閱讀引用之後,在查詢中粘貼上面的內容。我嘗試使用下界的通配符。請建議正確的理解與鏈接和例子。 – 2013-04-11 06:09:34

+0

但是'List <? super Long>'意味着「一個Long或超類的類型列表,但我不知道是什麼」 - 這意味着你不能爲其添加一個'Number'。 (它可能被創建爲'ArrayList ',它不應該包含非Long。) – 2013-04-11 06:11:43

回答

1

listNum可能是List<Long>的一個實例,並且您不能將Number添加到Long的列表中,因爲它會拋出類轉換異常。

解決方案:

  1. 使listNum一個List<? super Number>
  2. 使num一個Long
+0

這個例子是爲了理解下界有界通配符的正確用法。參考鏈接被粘貼在上面的查詢中。我想要將所有超類的ExportException存儲在列表中。我可以做嗎?上面的例子是否是正確的測試方法?我在理解下界通配符時錯了嗎? – 2013-04-11 06:13:07

+0

感謝Jon Skeet的提示,我已經寫了這段代碼來闡明Super與泛型的用法。評論解釋了這一切。 – 2013-04-30 02:59:50

0
package main.java.com.mysystems.generics; 

import java.rmi.RemoteException; 
import java.rmi.server.ExportException; 
import java.rmi.server.SocketSecurityException; 
import java.util.LinkedList; 
import java.util.List; 

//peCS 
//Consumer super- you want to add item i.e of super type to the collection. 
public class GenericSuper { 


    List<? super Long> listNum = new LinkedList <Number>();// listNum is variable that can be assigned list of type super class to Long. 
    //And you can put Long and its subclass. And you can only get Object type since it can hold anything from Long to Object. 

    List<? super ExportException> listExp= new LinkedList<RemoteException>(); // listExp is variable that can be assigned any list of type super class to ExportException. 
    // And you can put ExportException and all subclasses of ExportException to the list. And you can only get Object type since it can hold anything from ExportException to Object. 

    public List<? super ExportException> addList() 
    { 
     LinkedList <Number> numList = new LinkedList <Number>(); 

     Number num = 10.10; 
     numList.add(num); 
     listNum = numList; 
     //listNum.add(num); //Compilation error as only long or its subclass can be added. 
     listNum.add(20L); 

     for(Object e:listNum){ // Note you can only get Object type and will have to use instance of to do anything meaningful. 
      System.out.println(e); 
     } 
     SocketSecurityException sse = new SocketSecurityException("Hello"); 
     listExp.add(sse); 
     return listExp; 
     } 
    } 
0

問題不是泛型實現,而它的一個基本的Java集合框架的錯誤,其中可以不加號碼鍵入類型。泛型只是在編譯時解決它。泛型不是在這個地方,你會得到運行時異常,即ClassCastException。