JorgeO JorgeO - 8 months ago 46
Java Question

Best way to create an empty map in Java

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

What is the best way to create this empty map?


1) If the Map can be immutable:


// 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:

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

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

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:

new HashMap<String, String>();

(as tehblanx pointed out)

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

1) Immutable map:

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

Granted, no big benefits here compared to 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 that you can modify:

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

Maps contains similar factory methods for instantiating other types of maps as well, such as TreeMap or LinkedHashMap.