Java ArrayList and HashMap on-the-fly

后端 未结 7 1130
甜味超标
甜味超标 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:48

    You mean like this?

    public List buildList(String first, String second)
    {
         List ret = new ArrayList();
         ret.add(first);
         ret.add(second);
         return ret;
    }
    
    ...
    
    List names = buildList("Jon", "Marc");
    

    Or are you interested in the ArrayList constructor which takes a Collection? For example:

    String[] items = new String[] { "First", "Second", "Third" };
    // Here's one way of creating a List...
    Collection itemCollection = Arrays.asList(items);
    // And here's another
    ArrayList itemList = new ArrayList(itemCollection);
    

提交回复
热议问题