- 集合转数组
public class CoolectionToArrayDemo {
public static void main(String[] args) {
Collection<String> c = new ArrayList<>();
c.add("one");
c.add("two");
c.add("three");
c.add("four");
c.add("five");
System.out.println(c);
//默认返回object类型,其他需要定义
Object[] strs = c.toArray();
String[] s1 = c.toArray(new String[10]);
//定义的数组长度不足时也不会缩小,定义的数组就不要了,只参照类型时
String[] s2 = c.toArray(new String[2]);
//
System.out.println(Arrays.toString(s2));
System.out.println(s1.length);
//遍历数组需要toArrays,直接使用为引用
System.out.println(Arrays.toString(s1));
}
}
- toArray()默认返回object类型,其他需要定义
- 定义的数组长度不足时也不会缩小,定义的数组就不要了,只参照类型时
- 遍历数组需要toArrays,直接使用为引用
数组转集合
public class ArrayToCollectionDemo {
public static void main(String[] args) {
String[] strs = {
"one","two","three","four","five"};
System.out.println(Arrays.toString(strs));
//转换集合
List<String> list = Arrays.asList(strs);
System.out.println(list.size());
System.out.println(list);
//对集合元素的操作就是对原数组的操作
list.set(1,"2");
System.out.println(Arrays.toString(strs));
//本质上就是这个集合在操作这个数组
//因为数组长度固定,所以这个集合不能增删元素
//如果非要增删元素,只能再创建一个集合,将list中的内容添加到这个数组
List<String> list2 = new ArrayList<>();
list2.addAll(list);
list2.add("five");
System.out.println(list2);
//另一种操作
List<String> list3 = new ArrayList<>(list);
list3.add("five");
System.out.println(list3);
}
}
- 对集合元素的操作就是对原数组的操作
- 本质上就是这个集合在操作这个数组。因为数组长度固定,所以这个集合不能增删元素