我需要创建一个空地图。

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

问题是,上述代码产生这样的警告:类安全:选中投从地图哈希

什么是最好的方式来创建这个空地图吗?

有帮助吗?

解决方案

1) 如果地图可不可变的:

Collections.emptyMap()

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

你必须要使用后者有时,编译器不会自动找出什么样的地图是必要的(这是被称为 类型推理).例如,考虑一种宣布是这样的:

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

当穿过空地图直接向它,你必须要明确有关类型:

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

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

new HashMap<String, String>()

(作为 tehblanx指出)


增编:如果项目使用 番石榴, 您有以下选择:

1) 不可改变地图:

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

授予的,没有很大的好处在这里相比 Collections.emptyMap(). 从如果是的话,为什么不试:

这张地图的行为,并执行相对来 Collections.emptyMap(), 和最好主要是为了一致性和可维护性 代码。

2) 地图,你可以修改:

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

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


更新(2018年):上 Java9 或更新、最短代码,用于创建一个不可改变的空地图是:

Map.of()

...用新的 便利工厂的方法JEP269. 😎

其他提示

如果您需要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();
    }
  }

}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top