adding multiple entries to a HashMap at once in one statement

前端 未结 9 959
迷失自我
迷失自我 2020-12-04 06:27

I need to initialize a constant HashMap and would like to do it in one line statement. Avoiding sth like this:

  hashMap.put(\"One\", new Integer(1)); // add         


        
9条回答
  •  离开以前
    2020-12-04 06:52

    Here's a simple class that will accomplish what you want

    import java.util.HashMap;
    
    public class QuickHash extends HashMap {
        public QuickHash(String...KeyValuePairs) {
            super(KeyValuePairs.length/2);
            for(int i=0;i

    And then to use it

    Map Foo=QuickHash(
        "a", "1",
        "b", "2"
    );
    

    This yields {a:1, b:2}

提交回复
热议问题