List和数组相互转换

数组转List:

  1. Collections.addAll()
String[] strings = {"aa","bb","cc"};
List list = new ArrayList();
Collections.addAll(list, strings);
System.out.println(list.toString());
  1. 笨办法,循环添加数组元素
String[] strings = { "aa", "bb", "cc", "dd" };
List list = new ArrayList();
for (int i = 0; i < strings.length; i++) {
    list.add(strings[i]);
}
  1. Arrays.asList()
    返回一个受指定数组支持的固定大小的列表。所以不能做Add、Remove等操作。
String[] strings = { "aa", "bb", "cc", "dd" };
List list = new ArrayList();
list = Arrays.asList(strings);
// list.add("ee"); //使用aslist后的list是固定大小,不能添加或者删除
// list.remove(0);

List转数组:

  1. 用toArray方法
List list = new ArrayList();
list.add("aa");
list.add("bb");
list.add("cc");
list.add("dd");
String[] strs = new String[list.size()];
list.toArray(strs);
for (int i = 0; i < strs.length; i++) {
    System.out.println(strs[i]);
}
  1. 笨办法
List list = new ArrayList();
list.add("aa");
list.add("bb");
list.add("cc");
list.add("dd");
String[] strs = new String[list.size()];

for (int i = 0; i < list.size(); i++) {
    strs[i] = list.get(i);
}

for (int i = 0; i < strs.length; i++) {
    System.out.println(strs[i]);
}

你可能感兴趣的:(List和数组相互转换)