import java.util.HashMap;
import java.util.Map;
public class MapExample {
public static void main(String[] args) {
// 创建一个HashMap实例
Map<String, Integer> map = new HashMap<>();
// 向Map中添加键值对
map.put("Apple", 1);
map.put("Banana", 2);
map.put("Orange", 3);
// 获取指定键的值
System.out.println("Value for 'Apple': " + map.get("Apple"));
// 检查Map中是否包含某个键
if (map.containsKey("Banana")) {
System.out.println("Map contains key 'Banana'");
}
// 遍历Map中的所有键值对
for (Map.Entry<String, Integer> entry : map.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
// 删除指定键的键值对
map.remove("Orange");
// 获取Map的大小
System.out.println("Size of the map: " + map.size());
// 清空Map
map.clear();
System.out.println("Is the map empty? " + map.isEmpty());
}
}
HashMap
创建了一个名为map
的Map
对象。put
方法向map
中添加了三个键值对。get
方法根据键获取对应的值。containsKey
方法检查map
中是否包含某个键。entrySet
方法遍历map
中的所有键值对。remove
方法删除指定键的键值对。size
方法获取map
的大小。clear
方法清空map
,并使用isEmpty
方法检查map
是否为空。上一篇:java list map
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站