Java 中的 IdentityHashMap values() 方法

Java 中的 IdentityHashMap values() 方法

Java 中,IdentityHashMap 继承自 AbstractMap 类,实现了 Map 接口。与 HashMap 不同的是,IdentityHashMap 比较键时使用的是 运算符而不是 equals() 方法。在这篇文章中,我们将讨论 IdentityHashMap 中的 values() 方法。

IdentityHashMap 中的 values() 方法

values() 方法返回一个包含 IdentityHashMap 中所有值的 Collection 对象。返回的 Collection 是 IdentityHashMap 的视图,因此任何对视图进行的更改都将反映在 IdentityHashMap 中。

IdentityHashMap 的 values() 方法的声明如下:

public Collection<V> values()

该方法返回一个 Collection,其中包含 IdentityHashMap 中所有关联的值。如果 IdentityHashMap 为空,则返回空的 Collection。

以下示例演示了如何使用 IdentityHashMap 中的 values() 方法:

import java.util.Collection;
import java.util.IdentityHashMap;

public class IdentityHashMapDemo {
    public static void main(String[] args) {
        IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<String, String>();
        identityHashMap.put(new String("John"), "Doe");
        identityHashMap.put(new String("Tom"), "Smith");
        Collection<String> values = identityHashMap.values();
        System.out.println("Values: " + values); // 输出: Values: [Doe, Smith]
    }
}

在上面的示例中,我们创建了一个 IdentityHashMap 对象并将两个键和相应的值添加到它中。然后,我们使用 values() 方法获取 IdentityHashMap 的值并打印输出。

IdentityHashMap 值集合的修改

由于 IdentityHashMap 的 values() 方法返回的是 IdentityHashMap 的视图,因此修改这个视图中的元素会反映在 IdentityHashMap 中。以下示例演示了修改 IdentityHashMap 的值集合并在 IdentityHashMap 中查看这些修改:

import java.util.Collection;
import java.util.IdentityHashMap;

public class IdentityHashMapDemo {
    public static void main(String[] args) {
        IdentityHashMap<String, String> identityHashMap = new IdentityHashMap<String, String>();
        identityHashMap.put(new String("John"), "Doe");
        identityHashMap.put(new String("Tom"), "Smith");
        Collection<String> values = identityHashMap.values();
        System.out.println("Values before modification: " + values); // 输出: Values before modification: [Doe, Smith]
        values.remove("Smith");
        System.out.println("IdentityHashMap after modification: " + identityHashMap); // 输出: IdentityHashMap after modification: {John=Doe}
    }
}

在上面的示例中,我们获取 IdentityHashMap 的值集合,并从这个集合中移除了一个元素。然后,我们打印输出修改后的 IdentityHashMap,它不再包含 “Smith” 的值。

总结

在这篇文章中,我们讨论了 IdentityHashMap 中的 values() 方法。该方法返回一个包含 IdentityHashMap 中所有值的 Collection 对象。由于 IdentityHashMap 的 values() 方法返回的是 IdentityHashMap 的视图,因此任何对视图进行的更改都将反映在 IdentityHashMap 中。在您的代码中使用 IdentityHashMap.values() 可以帮助您方便地操作 IdentityHashMap 中的值。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程