Java ArrayList and HashMap on-the-fly

后端 未结 7 1133
甜味超标
甜味超标 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条回答
  •  -上瘾入骨i
    2021-01-31 07:56

    Use a nice anonymous initializer:

    List list = new ArrayList() {{
        add("a");
        add("b");
    }};
    

    Same goes for a Map:

    Map map = new HashMap() {{
        put("a", "a");
        put("b", "b");
    }};
    

    I find this the most elegant and readable.

    Other methods demand creating an array first, then converting it to a List - too expensive in my taste, and less readable.

提交回复
热议问题