在 Java 中创建空地图的最佳方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/636126/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 17:15:01  来源:igfitidea点击:

Best way to create an empty map in Java

javadictionarycollectionshashmap

提问by JorgeO

I need to create an empty map.

我需要创建一个空地图。

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

The problem is that the above code produces this warning: Type safety: Unchecked cast from Map to HashMap

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

What is the best way to create this empty map?

创建此空地图的最佳方法是什么?

采纳答案by Jonik

1)If the Map can be immutable:

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

Collections.emptyMap()

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

You'll have to use the latter sometimes when the compiler cannot automatically figure out what kind of Map is needed (this is called type inference). For example, consider a method declared like this:

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

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

When passing the empty Map directly to it, you have to be explicit about the type:

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

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

2)If you need to be able to modify the Map, then for example:

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

new HashMap<String, String>()

(as tehblanx pointed out)

(正如tehblanx指出的那样



Addendum: If your project uses Guava, you have the following alternatives:

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

1)Immutable map:

1)不可变映射:

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

Granted, no big benefits here compared to Collections.emptyMap(). From the Javadoc:

当然,与Collections.emptyMap(). 从 Javadoc

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

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

2)Map that you can modify:

2)可以修改的地图:

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

Mapscontains similar factory methods for instantiating other types of maps as well, such as TreeMapor LinkedHashMap.

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



Update (2018): On Java 9or newer, the shortest code for creating an immutable empty map is:

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

Map.of()

...using the new convenience factory methodsfrom JEP 269.

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

回答by AndreiM

If you need an instance of HashMap, the best way is:

如果你需要一个 HashMap 的实例,最好的方法是:

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

Since Map is an interface, you need to pick some class that instantiates it if you want to create an empty instance. HashMap seems as good as any other - so just use that.

由于 Map 是一个接口,如果你想创建一个空实例,你需要选择一些实例化它的类。HashMap 看起来和其他的一样好 - 所以就用它吧。

回答by Peter ?tibrany

Either Collections.emptyMap(), or if type inference doesn't work in your case,
Collections.<String, String>emptyMap()

或者Collections.emptyMap(),如果类型推断在您的情况下不起作用,
Collections.<String, String>emptyMap()

回答by Vitalii Fedorenko

Since in many cases an empty map is used for null-safe design, you can utilize the nullToEmptyutility method:

由于在许多情况下空映射用于空安全设计,因此您可以使用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()
    }
  }

}  

Similarly for sets:

同样对于集合:

class SetUtils {

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

}

and lists:

并列出:

class ListUtils {

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

}