繁体   English   中英

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

[英]Best way to create an empty map in Java

我需要创建一个空的 map。

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

问题是上面的代码产生了这个警告: Type safety: Unchecked cast from Map to HashMap

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

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

Collections.emptyMap()

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

有时,当编译器无法自动确定需要哪种Map时(这称为类型推断 ),您将不得不使用后者。 例如,考虑一个声明如下的方法:

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指出的那样


附录 :如果您的项目使用番石榴 ,您有以下替代方案:

1)不变的地图:

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

当然,与Collections.emptyMap()相比,这里没有什么好处。 来自Javadoc

此映射的行为与Collections.emptyMap()相当,并且主要用于代码的一致性和可维护性。

2)您可以修改的地图:

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

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


更新(2018) :在Java 9或更高版本上,创建不可变空映射的最短代码是:

Map.of()

...使用JEP 269的新便利工厂方法 😎

如果您需要HashMap的实例,最好的方法是:

fileParameters = new HashMap<String,String>();

由于Map是一个接口,因此如果要创建一个空实例,则需要选择一个实例化它的类。 HashMap看起来和其他任何一样好 - 所以就这样使用它。

无论是Collections.emptyMap() ,还是类型推断在您的情况下都不起作用,
Collections.<String, String>emptyMap()

由于在许多情况下空映射用于空安全设计,因此可以使用nullToEmpty实用程序方法:

class MapUtils {

  static <K,V> Map<K,V> nullToEmpty(Map<K,V> map) {
    if (map != null) {
      return map;
    } else {
       return Collections.<K,V>emptyMap(); // or guava ImmutableMap.of()
    }
  }

}  

同样对于集合:

class SetUtils {

  static <T> Set<T> nullToEmpty(Set<T> set) {
    if (set != null) {
      return set;
    } else {
      return Collections.<T>emptySet();
    }
  }

}

并列出:

class ListUtils {

  static <T> List<T> nullToEmpty(List<T> list) {
    if (list != null) {
      return list;
    } else {
      return Collections.<T>emptyList();
    }
  }

}

您可以使用:

Collections<String, String>.emptyMap();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM