在java中,在该类的泛型中使用特定的包装器类之后,我们不能在该类的任何静态方法或实例方法或实例变量中使用特定的包装类。另一个问题是只能接受Integer对象的构造函数也接受String(或任何其他包装类对象)。看看下面的代码,,这些编译错误背后的原因是什么?
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**
}
}发布于 2016-02-03 11:38:36
在这里,您没有使用“泛型中的包装类”,您只是将泛型类型变量命名为java.lang包中隐藏原始类的现有类。但是,您仍然可以使用完全限定的名称访问原始类:
java.lang.Integer val2 = new java.lang.Integer(2);对于有编译错误的其他地方也是如此。通常,最好避免与java.lang类冲突的名称。也许你真的想写点不同的东西,比如
public class Exp extends SomeOtherGenericClass<Integer> { ... }发布于 2016-02-03 11:57:30
尖括号中的类型是一个虚拟类型,稍后将替代实际类型。使用<T>是很常见的。您已经使用了一个真正的类型,<Integer>,它隐藏了系统类Integer,因此程序中的Integer不再引用java.lang.Integer,从而导致错误消息。
您的代码应该如下所示:
public class Exp<T> {
T val1;
...https://stackoverflow.com/questions/35175964
复制相似问题