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