2016-02-03 98 views
0

在java中,在使用特定包裝類的泛型後,我們不能在任何靜態方法或實例方法或實例變量中使用該特定包裝類類。另一個問題是隻能接受Integer對象接受字符串(或任何其他包裝類對象)的構造函數。看下面的代碼,這些編譯錯誤背後的原因是什麼?類泛型中使用的包裝類

public class Exp<Integer> { 
    Integer val1; 

    Integer val2=new Integer(2);//compilation error, cannot instantiate the type Integer 

    public Exp(Integer arg1){ 
     System.out.println(arg1); 
     val1=arg1; 
    } 

    public void lol(){ 
    //  Integer intValue2=new Integer(2);//compilation error, cannot make static reference to the non static type Integer 
    } 

    public static void main(String[] args){ 
     Exp obj1=new Exp(10); 
    //  Exp obj2=new Exp("Hello world"); 

    //  Exp<String> obj3=new Exp<String>("sss");// The constructor takes Integer arg, then why is string arg working perfectly with it? 
     String str="10"; 

     Character c=new Character('c');//works perfectly 
     Float f1=3.0f; 

     Integer intValue1=new Integer(2); //**compilation error, cannot make static reference to the non static type Integer** 

     Exp<Integer> obj4=new Exp<>(10); //**compilation error, cannot make static reference to the non static type Integer** 



    } 
} 
+1

有啥你的問題呢? – AdamSkywalker

+0

@AdamSkywalker無法理解編譯錯誤背後的原因。 – AnejaIshant

回答

1

這裏不使用「在仿製藥的包裝類」,你只是命名爲java.lang包裏面隱藏了原班現有類的泛型類型變量。但是你仍然可以訪問使用完全限定名原班:

java.lang.Integer val2 = new java.lang.Integer(2); 

同爲,你必須編譯錯誤等地。總的來說,最好避免與java.lang類衝突的名稱。可能你實際上想要寫一些不同的東西,比如

public class Exp extends SomeOtherGenericClass<Integer> { ... } 
+0

好吧,我使用的Integer只是一個變量(不是包裝類),而@Neil說我可以使用任何變量,它將像後面提供的實際類型的佔位符一樣,主要是在對象創造,對嗎? – AnejaIshant

1

尖括號中的類型是一個虛擬的,後面用實際類型代替。通常使用<T>。您已經使用了一個真實類型<Integer>,它隱藏了系統類Integer,因此您的程序中的Integer不再指代java.lang.Integer,從而導致出現錯誤消息。

您的代碼應該是這樣的:

public class Exp<T> { 
    T val1; 
    ...