Home Java中Array和List的相互转换
Post
Cancel

Java中Array和List的相互转换

Array转List

1
2
3
4
5
6
7
8
String[] array = {"string1", "string2", "string3"};
List<String> list = Arrays.asList(array);
//Arrays.asList产生一个Arrays内置的类,其中数组用final表示
// list.add("string4");  所以不能往其中添加元素

for(String s : list){
    System.out.println(s);
}

List转Array

1
2
3
4
5
6
7
8
9
10
List<String> list2 = new ArrayList<>();
list2.add("t1");
list2.add("t2");
list2.add("t3");
//toArray中不指定参数,只能转换为Object类型
String[] strings = list2.toArray(new String[list2.size()]);

for (String v : strings) {
    System.out.println(v);
}

参考:Java中Array和List的相互转换

This post is licensed under CC BY 4.0 by the author.