java怎么初始化map并赋值
Java中初始化Map并赋值有多种方式,具体取决于使用的Map实现类。以下是几种常用的方式:
- 使用HashMap初始化并赋值:
Map<String, Integer> map = new HashMap<>();
map.put("key1", 1);
map.put("key2", 2);
- 使用LinkedHashMap初始化并赋值:
Map<String, Integer> map = new LinkedHashMap<>();
map.put("key1", 1);
map.put("key2", 2);
- 使用TreeMap初始化并赋值:
Map<String, Integer> map = new TreeMap<>();
map.put("key1", 1);
map.put("key2", 2);
- 使用Map.of方法初始化并赋值(适用于Java 9及以上版本):
Map<String, Integer> map = Map.of("key1", 1, "key2", 2);
- 使用Map.entry方法初始化并赋值(适用于Java 8及以上版本):
Map<String, Integer> map = new HashMap<>();
map.putAll(Map.ofEntries(
Map.entry("key1", 1),
Map.entry("key2", 2)
));
注意:上述示例中的数据类型可以根据实际情况进行更改。
版权声明
本文仅代表作者观点,不代表米安网络立场。
上一篇:ubuntu虚拟机磁盘怎么扩容 下一篇:python怎么把列表变成字符串
发表评论:
◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。