Better Map Constructor

后端 未结 5 649
走了就别回头了
走了就别回头了 2021-01-02 10:13

Is there a more streamlined way to do the following?

Map map = new HashMap();
map.put(\"a\", \"apple\");
map.put(         


        
5条回答
  •  既然无缘
    2021-01-02 10:27

    No, there isn't, but I wrote a method to do exactly this, inspired by Objective-C NSDictionary class:

    public static Map mapWithKeysAndObjects(Object... objects) {
    
        if (objects.length % 2 != 0) {
            throw new IllegalArgumentException(
                    "The array has to be of an even size - size is "
                            + objects.length);
        }
    
        Map values = new HashMap();
    
        for (int x = 0; x < objects.length; x+=2) {
          values.put((String) objects[x], objects[x + 1]);
        }
    
        return values;
    
    }
    

提交回复
热议问题