1.强制转换放入泛型的对应
@Test
public void test() {
Map<Long,Object> map = new HashMap<>();
map.put((long) 3, 12);
System.out.println(map.get(3));
}
执行结果:
2.反编译结果如下:
@Test
public void test()
{
Map<Long, Object> map = new HashMap();
map.put(Long.valueOf(3L), Integer.valueOf(12));
System.out.println(map.get(Integer.valueOf(3)));
}
原因:Map.get(key)方法编译的时候对key的处理方式和map.put(key,val) 不一致。可以对比下图:
,put()编译检查了类型。而get()没有检查。
导致存取的对象不一致,所以取值为Null
结论:使用泛型之后,不要再使用强制转换类型的手段处理数据,尽量使用明细的数据对象,子泛型类就用 <? super T>