首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >类泛型中使用的包装类

类泛型中使用的包装类
EN

Stack Overflow用户
提问于 2016-02-03 11:35:59
回答 2查看 1.3K关注 0票数 0

在java中,在该类的泛型中使用特定的包装器类之后,我们不能在该类的任何静态方法或实例方法或实例变量中使用特定的包装类。另一个问题是只能接受Integer对象的构造函数也接受String(或任何其他包装类对象)。看看下面的代码,,这些编译错误背后的原因是什么?

代码语言:javascript
复制
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**



    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-02-03 11:38:36

在这里,您没有使用“泛型中的包装类”,您只是将泛型类型变量命名为java.lang包中隐藏原始类的现有类。但是,您仍然可以使用完全限定的名称访问原始类:

代码语言:javascript
复制
java.lang.Integer val2 = new java.lang.Integer(2);

对于有编译错误的其他地方也是如此。通常,最好避免与java.lang类冲突的名称。也许你真的想写点不同的东西,比如

代码语言:javascript
复制
public class Exp extends SomeOtherGenericClass<Integer> { ... }
票数 1
EN

Stack Overflow用户

发布于 2016-02-03 11:57:30

尖括号中的类型是一个虚拟类型,稍后将替代实际类型。使用<T>是很常见的。您已经使用了一个真正的类型,<Integer>,它隐藏了系统类Integer,因此程序中的Integer不再引用java.lang.Integer,从而导致错误消息。

您的代码应该如下所示:

代码语言:javascript
复制
public class Exp<T> {
    T val1;
    ...
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/35175964

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档