假设我有很多字符串变量(例如 100):
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
....
String str100 = "zzz";
我想将这些String变量添加到ArrayList中,我现在做的是
ArrayList<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
...
list.add(str100);
我很好奇,有没有办法使用循环?例如。
for(int i = 1; i <= 100; i++){
list.add(str+i)//something like this?
}
原文由 CSnerd 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用数组:
这个想法非常流行,以至于有内置的方法可以做到这一点。例如:
会将您的数组元素添加到现有列表中。 Also the
Collections
class (note thes
at the end) has static methods that work for allCollection
classes and do not require callingArrays.asList()
。例如:如果你只想要一个只有数组元素的列表,你可以在一行中完成:
编辑:Java API 中的许多其他类都支持此
addAll()
方法。它是 Collection 接口的一部分。 Other classes likeStack
,List
,Deque
,Queue
,Set
, and so forth implementCollection
因此addAll()
方法。 (是的,其中一些是接口,但它们仍然实现Collection
。)