Add multiple items to already initialized arraylist in java

前端 未结 6 1703
温柔的废话
温柔的废话 2020-11-27 16:45

I\'m googling it and can\'t seem to find the syntax. My arraylist might be populated differently based on a user setting, so I\'ve initialized it



        
6条回答
  •  一向
    一向 (楼主)
    2020-11-27 17:03

    If you have another list that contains all the items you would like to add you can do arList.addAll(otherList). Alternatively, if you will always add the same elements to the list you could create a new list that is initialized to contain all your values and use the addAll() method, with something like

    Integer[] otherList = new Integer[] {1, 2, 3, 4, 5};
    arList.addAll(Arrays.asList(otherList));
    

    or, if you don't want to create that unnecessary array:

    arList.addAll(Arrays.asList(1, 2, 3, 4, 5));
    

    Otherwise you will have to have some sort of loop that adds the values to the list individually.

提交回复
热议问题