在Java中将数组转换为ArrayList
我们可以使用以下方法将数组转换为arraylist。
使用Arrays.asList()方法-将所需的数组传递给此方法,并获取List 对象,并将其作为参数传递给ArrayList 类的构造函数。
Collections.addAll()方法-使用此方法之前创建一个新列表,然后使用此方法将数组元素添加到现有列表中。
迭代方法-创建一个新列表。迭代数组并将每个元素添加到列表中。
示例
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class Tester {
public static void main(String args[]) {
String[] array = {"a", "b", "c", "d", "e"};
//Method 1
List<String> list = Arrays.asList(array);
System.out.println(list);
//Method 2
List<String> list1 = new ArrayList<String>();
Collections.addAll(list1, array);
System.out.println(list1);
//Method 3
List<String> list2 = new ArrayList<String>();
for(String text:array) {
list2.add(text);
}
System.out.println(list2);
}
}输出结果
[a, b, c, d, e] [a, b, c, d, e] [a, b, c, d, e]
热门推荐
10 新婚过年祝福语大全简短
11 下雪宝宝生日祝福语简短
12 回国了祝福语简短英语
13 生日祝福语男人搞笑简短
14 店家搬家祝福语大全简短
15 六一互换礼物祝福语简短
16 见证求婚文案祝福语简短
17 学校职工祝福语大全简短
18 周末新人祝福语短句简短