gpt4 book ai didi

java - 在 Java 中创建空 map 的最佳方法

转载 作者:IT老高 更新时间:2023-10-28 11:26:26 25 4
gpt4 key购买 nike

我需要创建一个空 map 。

if (fileParameters == null)
fileParameters = (HashMap<String, String>) Collections.EMPTY_MAP;

问题是上面的代码产生了这个警告:类型安全:从 Map 到 HashMap 的未经检查的强制转换

创建这个空 map 的最佳方法是什么?

最佳答案

1) 如果 Map 可以是不可变的:

Collections.emptyMap()

// or, in some cases:
Collections.<String, String>emptyMap()

当编译器无法自动确定需要哪种 Map 时(称为 type inference),有时您必须使用后者。例如,考虑这样声明的方法:

public void foobar(Map<String, String> map){ ... }

当直接将空 Map 传递给它时,您必须明确类型:

foobar(Collections.emptyMap());                 // doesn't compile
foobar(Collections.<String, String>emptyMap()); // works fine

2)如果您需要能够修改 map ,那么例如:

new HashMap<String, String>()

(如 tehblanx pointed out )


附录:如果您的项目使用 Guava ,您有以下选择:

1) 不可变映射:

ImmutableMap.of()
// or:
ImmutableMap.<String, String>of()

当然,与 Collections.emptyMap() 相比,这里没有什么大的好处。 From the Javadoc :

This map behaves and performs comparably to Collections.emptyMap(), and is preferable mainly for consistency and maintainability of your code.

2) 可以修改的 map :

Maps.newHashMap()
// or:
Maps.<String, String>newHashMap()

Maps也包含用于实例化其他类型 map 的类似工厂方法,例如 TreeMapLinkedHashMap .


更新(2018 年):在 Java 9 或更高版本中,用于创建不可变空 map 的最短代码是:

Map.of()

...使用新的 convenience factory methods来自 JEP 269 . 😎

关于java - 在 Java 中创建空 map 的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/636126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com