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?
This question is related to
java
dictionary
collections
hashmap
Since in many cases an empty map is used for null-safe design, you can utilize the nullToEmpty
utility method:
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();
}
}
}
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.
What about :
Either Collections.emptyMap()
, or if type inference doesn't work in your case,
Collections.<String, String>emptyMap()
Source: Stackoverflow.com