案例
时间: 2023-09-08 20:08:48 浏览: 26
以下是一个使用IdentityHashMap的简单示例:
```java
import java.util.IdentityHashMap;
public class IdentityHashMapExample {
public static void main(String[] args) {
// 创建一个IdentityHashMap对象
IdentityHashMap<Integer, String> map = new IdentityHashMap<>();
// 添加键值对
Integer key1 = new Integer(1);
Integer key2 = new Integer(1);
map.put(key1, "Value 1");
map.put(key2, "Value 2");
// 获取值
System.out.println(map.get(key1)); // 输出 "Value 1"
System.out.println(map.get(key2)); // 输出 "Value 2"
// 输出map的大小
System.out.println("Size of map is: " + map.size()); // 输出 "Size of map is: 2"
}
}
```
在上面的示例中,我们创建了一个IdentityHashMap对象,并向其添加了两个键值对,其中键都是Integer类型的对象。尽管这两个对象的值相同,但它们具有不同的内存地址,因此在IdentityHashMap中被视为两个不同的键。当我们使用这两个键来获取值时,我们得到了不同的结果。最后,我们输出了map的大小,它包含了两个键值对。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)