tags:

views:

1130

answers:

6

I need to create an empty map if the map its null.

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

The problem is that I get a code warning: Type safety: Unchecked cast from Map to HashMap what its the best way to create this emptyMap.

+2  A: 

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

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.

tehblanx
+7  A: 

The emptyMap method of the Collections class.

TofuBeer
+5  A: 

Collections.emptyMap()

basszero
The problem was that this map can only be applied to a Map object not a HashMap
JorgeO
You should (generally) avoid declaring objects of their specific types and use the interface (or abstract parent) instead. Try to avoid "HashMap<String, String> foo;" and use "Map<String, String> foo;" instead
TofuBeer
+1 TofuBeer (if only I could)
matt b
+2  A: 

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

Peter Štibraný
+8  A: 

If the Map can be immutable:

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. For example, consider a method declared like this:

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

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

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

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

new HashMap<String,String>();

(as tehblanx pointed out)

Jonik
In most cases, type inference works (ie. map = Collections.emptyMap() works)
Sébastien RoccaSerra
Yeah, true. I edited the answer to be a little more comprehensive.
Jonik
A: 

What about :

Map<String, String> s = Collections.emptyMap();

OscarRyz
You won't be able to modify an empty map created that way.
javashlook