Java HashMap 示例:逐行解析代码
本示例代码展示了 Java 中 HashMap 的常见用法。下面将逐行解释代码的含义:
HashMap<String, Integer> myHashMap = new HashMap<>();
myHashMap.put('apple', 5);
myHashMap.put('banana', 10);
myHashMap.put('orange', 7);
int count = myHashMap.get('apple');
boolean containsKey = myHashMap.containsKey('banana');
int size = myHashMap.size();
myHashMap.remove('orange');
boolean isEmpty = myHashMap.isEmpty();
-
HashMap<String, Integer> myHashMap = new HashMap<>();:创建一个名为myHashMap的HashMap对象。HashMap是一个键值对存储结构,这里它被指定为存储字符串作为键和整数作为值的映射关系。 -
myHashMap.put('apple', 5);:将键为 'apple',值为 5 的键值对添加到myHashMap中。 -
myHashMap.put('banana', 10);:将键为 'banana',值为 10 的键值对添加到myHashMap中。 -
myHashMap.put('orange', 7);:将键为 'orange',值为 7 的键值对添加到myHashMap中。 -
int count = myHashMap.get('apple');:获取键为 'apple' 的值,并将其赋给变量count。 -
boolean containsKey = myHashMap.containsKey('banana');:检查myHashMap是否包含键 'banana',并将结果赋给变量containsKey。 -
int size = myHashMap.size();:获取myHashMap中键值对的数量,并将结果赋给变量size。 -
myHashMap.remove('orange');:删除键为 'orange' 的键值对。 -
boolean isEmpty = myHashMap.isEmpty();:检查myHashMap是否为空,即是否没有任何键值对,并将结果赋给变量isEmpty。
通过使用 HashMap,您可以方便地存储和操作键值对映射关系。您可以使用 put 方法将键值对添加到 HashMap 中,使用 get 方法获取特定键的值,使用 containsKey 方法检查键是否存在,使用 size 方法获取键值对的数量,使用 remove 方法删除指定键的键值对,使用 isEmpty 方法检查 HashMap 是否为空。
请注意,HashMap 是Java集合框架中的一个常用类,提供了丰富的方法和功能来操作键值对映射关系。您可以根据具体的需求使用它们的方法来添加、删除、查找键值对,以及遍历 HashMap 中的元素等操作。
原文地址: https://www.cveoy.top/t/topic/ciSf 著作权归作者所有。请勿转载和采集!