How can I initialise a static Map?

前端 未结 30 1550
慢半拍i
慢半拍i 2020-11-22 08:43

How would you initialise a static Map in Java?

Method one: static initialiser
Method two: instance initialiser (anonymous subclass) or some other m

30条回答
  •  不知归路
    2020-11-22 09:26

    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 keyClazz,
                Class valClazz,
                Object...keyValues)
        {
            return Collections.unmodifiableMap(makeMap(
                keyClazz,
                valClazz,
                keyValues));
        }
    
        public static  HashMap makeMap(
                Class keyClazz,
                Class 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 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);
            }
        }
    }
    

提交回复
热议问题