Is there a best practice for writing maps literal style in Java?

前端 未结 9 1842
感情败类
感情败类 2020-12-24 03:03

In short, if you want to write a map of e.g. constants in Java, which in e.g. Python and Javascript you would write as a literal,

T CON         


        
9条回答
  •  执念已碎
    2020-12-24 03:43

    You can write yourself a quick helper function:

    @SuppressWarnings("unchecked")
    public static  Map ImmutableMap(Object... keyValPair){
        Map map = new HashMap();
    
        if(keyValPair.length % 2 != 0){
            throw new IllegalArgumentException("Keys and values must be pairs.");
        }
    
        for(int i = 0; i < keyValPair.length; i += 2){
            map.put((K) keyValPair[i], (V) keyValPair[i+1]);
        }
    
        return Collections.unmodifiableMap(map);
    }
    

    Note the code above isn't going to stop you from overwriting constants of the same name, using CONST_1 multiple places in your list will result in the final CONST_1's value appearing.

    Usage is something like:

    Map constants = ImmutableMap(
        "CONST_0", 1.0,
        "CONST_1", 2.0
    );
    

提交回复
热议问题