在java中将多个项目添加到已经初始化的arraylist [英] Add multiple items to already initialized arraylist in java

查看:22
本文介绍了在java中将多个项目添加到已经初始化的arraylist的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在谷歌上搜索它,似乎找不到语法.我的 arraylist 可能会根据用户设置进行不同的填充,所以我已经对其进行了初始化

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

ArrayList<Integer> arList = new ArrayList<Integer>();

现在我想添加数百个整数而不用 arList.add(55);

And now I'd like to add hundred of integers without doing it one by one with arList.add(55);

推荐答案

如果您有另一个列表,其中包含您想要添加的所有项目,您可以执行 arList.addAll(otherList).或者,如果您总是将相同的元素添加到列表中,您可以创建一个初始化为包含所有值的新列表,并使用 addAll() 方法,类似于

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.

这篇关于在java中将多个项目添加到已经初始化的arraylist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆