java hashmap int,java:HashMap< String,int>不工作

本文探讨了Java中HashMap使用时遇到的问题,重点在于为何不能直接使用原始类型作为泛型参数,并解释了类型擦除的概念。通过实例说明了如何通过自动装箱和拆箱操作来解决这一问题,以及为什么`get()`方法可能导致空指针异常。

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

HashMap doesn't seem to work but HashMap does work.

Any ideas why?

解决方案

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

Map myMap = new HashMap();

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 myMap = new HashMap();

Map map2 = (Map)myMap;

map2.put(3, "foo");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值