Java ArrayList and HashMap on-the-fly

后端 未结 7 1132
甜味超标
甜味超标 2021-01-31 07:07

Can someone please provide an example of creating a Java ArrayList and HashMap on the fly? So instead of doing an add() or put()

7条回答
  •  一向
    一向 (楼主)
    2021-01-31 07:54

    Arrays can be converted to Lists:

    List al = Arrays.asList("vote", "for", "me"); //pandering
    

    Note that this does not return an ArrayList but an arbitrary List instance (in this case it’s an Array.ArrayList)!

    Bruno's approach works best and could be considered on the fly for maps. I prefer the other method for lists though (seen above):

    Map map = new HashMap() {
     {
        put("key1", "value1");
        put("key2", "value2");
     }
    };
    

提交回复
热议问题