Java 中的 IdentityHashMap 类

java 8object oriented programmingprogramming更新于 2025/6/26 20:22:17

IdentityHashMap 类与 HashMap 类似,不同之处在于它在比较元素时使用引用相等性。此类不是通用的 Map 实现。虽然此类实现了 Map 接口,但它故意违反了 Map 的通用约定,该约定要求在比较对象时使用 equals 方法。

以下是 IdentityHashMap 类的一些方法 −

Sr.No方法 &说明
1void clear()
从此映射中删除所有映射。
2Object clone()
返回此身份哈希映射的浅表副本:键和值本身不会被克隆。
3boolean containsKey(Object key)
测试指定的对象引用是否是此身份哈希映射中的键。
4boolean containsValue(Object value)
测试指定的对象引用是否是此身份哈希映射中的值。
5Set entrySet()
返回此映射中包含的映射关系的集合视图。
6boolean equals(Object o)
比较指定对象与此映射是否相等。
7Object get(Object key)
返回此身份哈希映射中指定键所映射到的值;如果映射不包含此键的映射,则返回 null。
8int hashCode()
返回此映射的哈希码值。

以下是在 Java 中实现 IdentityHashMap 类的示例 −

示例

import java.util.*;
public class Main {
   public static void main(String args[]) {
      IdentityHashMap iHashMap = new IdentityHashMap();
      iHashMap.put("John", new Integer(10000));
      iHashMap.put("Tim", new Integer(25000));
      iHashMap.put("Adam", new Integer(15000));
      iHashMap.put("Katie", new Integer(30000));
      iHashMap.put("Jacob", new Integer(45000));
      iHashMap.put("Steve", new Integer(23000));
      iHashMap.put("Nathan", new Integer(25000));
      iHashMap.put("Amy", new Integer(27000));
      Set set = iHashMap.entrySet();
      Iterator iterator = set.iterator();
      while(iterator.hasNext()) {
         Map.Entry map = (Map.Entry)iterator.next();
         System.out.print(map.getKey() + ": ");
         System.out.println(map.getValue());
      }
      System.out.println();
      System.out.println("Size of IdentintyHashMap: "+iHashMap.size());
      int bonus = ((Integer)iHashMap.get("Amy")).intValue();
      iHashMap.put("Amy", new Integer(bonus + 5000));
      System.out.println("Amy's salary after bonus = " + iHashMap.get("Amy"));
      int deductions = ((Integer)iHashMap.get("Steve")).intValue();
      iHashMap.put("Steve", new Integer(deductions - 3000));
      System.out.println("Steve's salary after deductions = " + iHashMap.get("Steve"));
   }
}

输出

Steve: 23000
Adam: 15000
Katie: 30000
Nathan: 25000
Tim: 25000
Amy: 27000
John: 10000
Jacob: 45000
Size of IdentintyHashMap: 8
Amy's salary after bonus = 32000
Steve's salary after deductions = 20000

相关文章