在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**
}
}
有啥你的問題呢? – AdamSkywalker
@AdamSkywalker無法理解編譯錯誤背後的原因。 – AnejaIshant