3.2、HashMap(上)
3.2.1、HashMap常用的API有哪些?
答:
HashMap是Java中常用的使用键值对存储数据的集合类,它提供了一系列的API来操作和管理存储的数据。
下面是常用的HashMap的API及其示例代码:
- put(key, value):将指定的键值对添加到HashMap中。也可做修改。
//添加
HashMap<String, Integer> hashMap = new HashMap<>();
hashMap.put("apple", 3);
hashMap.put("banana", 5);
//修改
hashMap.put("apple",10);
- get(key):根据指定的键获取对应的值。
Integer count = hashMap.get("apple");
System.out.println(count); // 输出:3
- containsKey(key):判断HashMap中是否包含指定的键。
boolean containsKey = hashMap.containsKey("banana");
System.out.println(containsKey); // 输出:true
- containsValue(value):判断HashMap中是否包含指定的值。
boolean containsValue = hashMap.containsValue(5);
System.out.println(containsValue); // 输出:true
- remove(key):根据指定的键从HashMap中移除对应的键值对。
hashMap.remove("apple");
- size():返回HashMap中键值对的数量。
int size = hashMap.size();
System.out.println(size); // 输出:1
- keySet():返回HashMap中所有键的集合。
Set<String> keys = hashMap.keySet();
for (String key : keys) {
System.out.println(key);
}
- values():返回HashMap中所有值的集合。
Collection<Integer> values = hashMap.values();
for (Integer value : values) {
System.out.println(value);
}
- entrySet():返回HashMap中所有键值对的集合。
Set<Map.Entry<String, Integer>> entries = hashMap.entrySet();
for (Map.Entry<String, Integer> entry : entries) {
System.out.println(entry.getKey() + ": " + entry.getValue());
}
以上是HashMap常用的API及其代码示例,可以实现对HashMap的添加、获取、判断、移除以及遍历等操作。关键还是要在业务中常用才能加深记忆。