How would you initialise a static Map
in Java?
Method one: static initialiser
Method two: instance initialiser (anonymous subclass)
or
some other m
If you want something terse and relatively safe, you can just shift compile-time type checking to run-time:
static final Map map = MapUtils.unmodifiableMap(
String.class, Integer.class,
"cat", 4,
"dog", 2,
"frog", 17
);
This implementation should catch any errors:
import java.util.HashMap;
public abstract class MapUtils
{
private MapUtils() { }
public static HashMap unmodifiableMap(
Class extends K> keyClazz,
Class extends V> valClazz,
Object...keyValues)
{
return Collections.unmodifiableMap(makeMap(
keyClazz,
valClazz,
keyValues));
}
public static HashMap makeMap(
Class extends K> keyClazz,
Class extends V> valClazz,
Object...keyValues)
{
if (keyValues.length % 2 != 0)
{
throw new IllegalArgumentException(
"'keyValues' was formatted incorrectly! "
+ "(Expected an even length, but found '" + keyValues.length + "')");
}
HashMap result = new HashMap(keyValues.length / 2);
for (int i = 0; i < keyValues.length;)
{
K key = cast(keyClazz, keyValues[i], i);
++i;
V val = cast(valClazz, keyValues[i], i);
++i;
result.put(key, val);
}
return result;
}
private static T cast(Class extends T> clazz, Object object, int i)
{
try
{
return clazz.cast(object);
}
catch (ClassCastException e)
{
String objectName = (i % 2 == 0) ? "Key" : "Value";
String format = "%s at index %d ('%s') wasn't assignable to type '%s'";
throw new IllegalArgumentException(String.format(format, objectName, i, object.toString(), clazz.getSimpleName()), e);
}
}
}