【问题标题】:How IdentityHashMap v get(key) methods works in these below situationIdentityHashMap v get(key) 方法在以下情况下如何工作
【发布时间】:2016-04-12 17:34:12
【问题描述】:
import java.util.HashMap;
import java.util.IdentityHashMap;
import java.util.Map;


public class IdentityHashMapExample {
    public static void main(String args[]){

        // Created HashMap and IdentityHashMap objects
        Map hashmapObject = new HashMap();

        Map identityObject = new IdentityHashMap();

        // Putting  keys and values in HashMap and IdentityHashMap Object

        hashmapObject.put(new String("key") ,"Google"); 

        hashmapObject.put(new String("key") ,"Facebook"); 

        identityObject.put(new String("identityKey") ,"Google"); 

        identityObject.put(new String("identityKey") ,"Facebook"); 
        // Print HashMap and IdentityHashMap Size : After adding  keys

        System.out.println("HashMap after adding key :"+ hashmapObject);
        System.out.println("Getting value from HashMap :"+ hashmapObject.get("key"));

        System.out.println("IdentityHashMap after adding key :"+ identityObject);
        // why get(key) method return the null value in case of identityHash Map 

        System.out.println("Getting value from IdentityHashMap :" + identityObject.get("identityKey"));
    }
}

【问题讨论】:

  • 欢迎来到 Stack Overflow。请花一些时间重新格式化您的代码 - 使用预览来检查它的显示是否符合您的预期 - 并将您的描述放在代码之外
  • 您期待什么? new String("identityKey") != "identityKey".

标签: java collections concurrency


【解决方案1】:

来自IdentityHashMap的javadoc:

该类使用哈希表实现 Map 接口,使用 比较键时引用相等代替对象相等 (和价值观)。换句话说,在 IdentityHashMap 中,两个键 k1 和 当且仅当 (k1==k2) 时,k2 才被认为是相等的。 (在法线地图中 实现(如 HashMap)两个键 k1 和 k2 被认为是相等的 当且仅当 (k1==null ? k2==null : k1.equals(k2)).)

因此,如果您尝试使用插入值的相同键引用检索值,您将获得该值。但是如果你尝试使用差异键引用来获取值(即使它是相等的),你会得到 null。

【讨论】:

    【解决方案2】:

    对于 IdentityHashMap 键是使用 '==' 运算符比较的,而在 HashMap 中则使用 equals()。 当您执行 new String("key") 时,它总是会在

    中创建一个新对象

    堆内存

    。另一方面,如果您使用字符串文字语法创建对象,例如"key",它可能会从

    返回一个现有对象

    字符串池

    或在池中创建一个。 因此,使用 equals() 时,两者在比较内容时都相同,但 '==' 将比较两种情况下不同的引用(因此在 IdentityHashMap 的情况下您无法获取对象)。

    【讨论】:

      猜你喜欢
      • 2013-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多