Java 简明教程
Java IdentityHashMap Class
Introduction
Java IdentityHashMap 类使用哈希表实现 Map 接口,在比较键(和值)时使用引用相等性来代替对象相等性。以下是有关 IdentityHashMap 的重要几点:
The Java IdentityHashMap class implements the Map interface with a hash table, using reference-equality in place of object-equality when comparing keys (and values).Following are the important points about IdentityHashMap −
-
This class provides all of the optional map operations, and permits null values and the null key.
-
This class makes no guarantees as to the order of the map; in particular, it does not guarantee that the order will remain constant over time.
-
In an IdentityHashMap, two keys k1 and k2 are considered equal if and only if (k1==k2), while in Map implementations (like HashMap) two keys k1 and k2 are considered equal if and only if (k1==null ? k2==null : k1.equals(k2)).
Class declaration
以下是 java.util.IdentityHashMap 类的声明:
Following is the declaration for java.util.IdentityHashMap class −
public class IdentityHashMap<K,V>
extends AbstractMap<K,V>
implements Map<K,V>, Serializable, Cloneable
Methods inherited
此类从以下类中继承方法:
This class inherits methods from the following classes −
-
java.util.AbstractMap
-
java.util.Object
Adding a Key-Value Mapping in an IdentityHashMap Example
以下示例展示了 Java IdentityHashMap put() 方法的用法,以将几个值放入映射中。我们创建了一个 Integer,Integer 的映射对象。然后使用 put() 方法添加了一些条目,然后打印映射。
The following example shows the usage of Java IdentityHashMap put() method to put few values in a Map. We’ve created a Map object of Integer,Integer. Then few entries are added using put() method and then map is printed.
package com.tutorialspoint;
import java.util.IdentityHashMap;
public class IdentityHashMapDemo {
public static void main(String args[]) {
// create identity map
IdentityHashMap<Integer,Integer> newmap = new IdentityHashMap<>();
// populate identity map
newmap.put(1, 1);
newmap.put(2, 2);
newmap.put(3, 3);
System.out.println("Map elements: " + newmap);
}
}
让我们编译并运行以上的程序,这会生成以下结果:
Let us compile and run the above program, this will produce the following result.
Map elements: {2=2, 3=3, 1=1}