在java中,在类的泛型中使用特定的包装类后,我们不能在任何静态方法或实例方法中使用该特定的包装类,或者该类的实例变量。另一个问题是只能接受 Integer 对象的构造函数也接受 Strings(或任何其他包装类对象)。看下面的代码,这些编译错误背后的原因是什么?
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**
}
}
最佳答案
这里您没有使用“泛型中的包装类”,您只是将泛型类型变量命名为 java.lang
包中的现有类,该包隐藏了原始类。但是,您仍然可以使用完全限定名称访问原始类:
java.lang.Integer val2 = new java.lang.Integer(2);
其他有编译错误的地方也是如此。一般来说,最好避免与 java.lang 类冲突的名称。也许你实际上想写一些不同的东西,比如
public class Exp extends SomeOtherGenericClass<Integer> { ... }
关于java - 类泛型中使用的包装类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35175964/