zoukankan      html  css  js  c++  java
  • Difference Between HashMap and IdentityHashMap--转

    原文地址: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 IdentityHashMap 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.

    import java.util.HashMap; 
    import java.util.IdentityHashMap;
    import java.util.Map;

    public class IdentityMapDemo {

    public static void main(String[] args) {
    Map identityMap = new IdentityHashMap();
    Map hashMap = new HashMap();
    identityMap.put("a", 1);
    identityMap.put(new String("a"), 2);
    identityMap.put("a", 3);
    hashMap.put("a", 1);
    hashMap.put(new 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.

     
    k1.equals(k2)
     

    instead of equality operator.

    When you run the above code the result will be

     
    Identity Map KeySet Size :: 2

    Hash Map KeySet Size :: 1
     

    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.

  • 相关阅读:
    C#呓语
    引起超时的原因及表解锁的方法<转>
    如何使用数据库引擎优化顾问优化数据库 <转>
    缩短IIS应用池回收时间,减少IIS假死<转>
    Microsoft Silverlight 4 Tools for Visual Studio 2010中文版本
    系统统一验证(IHttpHandlerFactory)<转>
    解决CSS BUG的顺口溜<转>
    重建索引提高SQL Server性能<转>
    .NET调用osql.exe执行sql脚本创建表和存储过程<转>
    SQL SERVER性能优化综述<转>
  • 原文地址:https://www.cnblogs.com/davidwang456/p/6026280.html
Copyright © 2011-2022 走看看