在Java中使用generic arguments时的基本问题

本文探讨了在Java中使用HashMap时遇到的一个常见错误——将基本数据类型用于泛型参数,并解释了为什么不能这样做。文章引用了Stack Overflow上的一个回答来详细说明自动装箱/拆箱的过程以及类型擦除的概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

      问题怎么来的?

      在编码时,声明一个HashMap类型的变量时,在generic arguments部分将Integer写为了int,像下面这样:

HashMap<int, String> var;

      未等编译,IDE已经给出了提示,有问题。


      问题原因:Java中,在generic arguments不能使用基本数据类型,比如int等。


      对这个问题的回答,可以看看下面这个web:

      http://stackoverflow.com/questions/1780385/java-hashmapstring-int-not-working

      其中,回答者cletus,还就auto-boxing/unboxing进行说明了。下面是其回答的原文:

         You can't use primitive types as generic arguments in Java. Use instead:

        Map<String, Integer> myMap = new HashMap<String, Integer>();

        With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:

        myMap.put("foo", 3);

        instead of:

        myMap.put("foo", new Integer(3));

        Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:

        int i = myMap.get("foo");

        instead of:

        int i = myMap.get("foo").intValue();

        The implicit call to intValue() means if the key isn't found it will generate a NullPointerException, for example:

        int i = myMap.get("bar"); // NullPointerException

        The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:

        Integer i = (Integer)myMap.get("foo");

        To give you an example, this code is perfectly legal:

        Map<String, Integer> myMap = new HashMap<String, Integer>();
        Map<Integer, String> map2 = (Map<Integer, String>)myMap;
        map2.put(3, "foo");


      另外,附上一篇关于Java generics的文章,它的内容以及附录的参考资料,有帮助。

      多角度看 Java 中的泛型

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值