加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

Difference Between HashMap and IdentityHashMap--转

发布时间:2020-12-14 06:21:58 所属栏目:Java 来源:网络整理
导读:原文地址:https://dzone.com/articles/difference-between-hashmap-and Most of the time I use HashMap whenever a map kinda object is needed. When reading some blog I came across?in Java. It is good to understand the differences between the tw

原文地址:https://dzone.com/articles/difference-between-hashmap-and

Most of the time I use HashMap whenever a map kinda object is needed. When reading some blog I came across?in Java. It is good to understand the differences between the two because you never know when you will see them flying across your code and you trying to find out why is ?this kinda Map is used here.

IdentityHashMap as name suggests uses the equality operator(==) for comparing the keys. So when you put any Key Value pair in it the Key Object is compared using == operator.

java.util.HashMap; java.util.IdentityHashMap; java.util.Map; IdentityMapDemo { main(String[] args) { Map identityMap = IdentityHashMap(); Map hashMap = HashMap(); identityMap.put("a",1); identityMap.put( String("a"),2);identityMap.put("a",3);hashMap.put("a",1); hashMap.put( String("a"),2);hashMap.put("a",3);System.out.println("Identity Map KeySet Size :: " + identityMap.keySet().size()); System.out.println("Hash Map KeySet Size :: " + hashMap.keySet().size()); } }

On the other hand HashMap uses equals method to determine the uniqueness of the Key.

instead of equality operator.

When you run the above code the result will be

The Keysize of Identity Map is 2 because here?a?and?new String(“a”)?are considered two different Object. The comparison is done using?==?operator.

For HashMap the keySize is 1 because K1.equals(K2) returns true for all three Keys and hence it keep on removing the old value and updating it with the new one.

These both Maps will behave in same manner if they are used for Keys which are user defined Object and doesn’t overrides equals method.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读