泛型在HashMap实现中 [英] Generics in HashMap implementation

查看:104
本文介绍了泛型在HashMap实现中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java实现中,我发现
$ b

  transient Entry []表; 
在构造函数中初始化为
table = new Entry [capacity];

我知道并明白创建泛型数组是不被允许的,但是我不明白的是整个事情起作用。我的意思是当我们做类似于

  HashMap< Integer,String> hMap = new HashMap< Integer,String>(); 

上面的代码如何导致创建类型为的整数数组< Integer ,String>



好的,很少有人无法理解我在问什么。要重新说明我所要求的是做什么事情的重点是什么

  HashMap< Integer,String> hMap = new HashMap< Integer,String>(); 

当它不导致

 条目<整数,字符串> 


解决方案

> Entry< K,V> 类型

的对象

  static class Entry< K,V>实现Map.Entry< K,V> 

不提供泛型类型参数( source )。这是允许的,但它理解编译器不再保证类型安全。例如,在代码中的其他地方,您可以编写

 条目< K,V> e =表[bucketIndex]; 

并且编译器会让你这样做。如果您确实知道您始终将元素 table [] 设置为 null Entry< ; K,V> ,那么你就知道赋值是正确的。



原因是没有问题的是Java中的泛型通过类型擦除来实现,即在入口< K,V> 对象入口<整数,整数> 条目< String,Long>


In the Java implementation, I found

 transient Entry[] table; 
 which is initiated in constructor as
 table = new Entry[capacity];

I know and understand that creating generic array is not allowed but then what I fail to understand is that how the whole thing works. I mean when we do something like

HashMap<Integer, String> hMap = new HashMap<Integer, String>();

How does above codes leads to creating an Entry array of type <Integer, String>

Well, few people are not able to understand what I am asking. To rephrase what I am asking is what is the point in doing something like

HashMap<Integer, String> hMap = new HashMap<Integer, String>();

When it does not result in

Entry<Integer, String>

解决方案

The implementation makes an array of Entry<K,V> objects of type

static class Entry<K,V> implements Map.Entry<K,V>

without providing generic type parameters (source). This is allowed, but it comes with understanding that the compiler is no longer guarantees type safety. For example, in other places in code you could write

Entry<K,V> e = table[bucketIndex];

and the compiler will let you do that. If you know for sure that you always set elements of table[] to null or Entry<K,V>, then you know that the assignment is correct.

The reason this works without a problem is that generic types in Java are implemented through type erasure, i.e. there is no difference at runtime between Entry<K,V> objects Entry<Integer,Integer> and Entry<String,Long>.

这篇关于泛型在HashMap实现中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆