将多个编号的对象添加到 ArrayList
问题描述:
假设我有很多字符串变量(例如 100 个):
Suppose I have a lot of String Variables(100 for example):
String str1 = "abc";
String str2 = "123";
String str3 = "aaa";
....
String str100 = "zzz";
我想把这些String变量添加到ArrayList中,我现在要做的是
I want to add these String variables to ArrayList, what I am doing now is
ArrayList<String> list = new ArrayList<String>();
list.add(str1);
list.add(str2);
list.add(str3);
...
list.add(str100);
我很好奇,有没有办法使用循环?例如.
I am curious, is there a way to use a loop? For example.
for(int i = 1; i <= 100; i++){
list.add(str+i)//something like this?
}
答
使用数组:
String[] strs = { "abc","123","zzz" };
for(int i = 0; i < strs.length; i++){
list.add(strs[i]); //something like this?
}
这个想法非常流行,以至于有内置的方法可以做到这一点.例如:
This idea is so popular that there's built-in methods to do it. For example:
list.addAll( Arrays.asList(strs) );
会将您的数组元素添加到现有列表中.如果你只想要一个只有数组元素的列表,你可以在一行上完成:
will add your array elements to an existing list. If you just want a list with only the array elements, you can do it on one line:
List<String> list = Arrays.asList( strs );