由于集合中存的是引用数据类型(对象)
int 数组中存的是基本数据类型,所以转化时,要注意。
public class Test4 {
public static void main(String [] args){
//1.数组转集合
//1.1.直接添加
List arr1=Arrays.asList(1,"a","ccc");
System.out.println(arr1);//[1, a, ccc]
//1.2.将Object数组转为list,注意,list中添加的要是对象
Integer [] integerarr = new Integer[]{1,3,6,7};
List arr2=Arrays.asList(integerarr);
System.out.println(arr2);//[1, 3, 6, 7]
//注意,添加的要是对象,不是数组,否则下面就将整个int[]当成一个整体,
int [] intarr = new int[]{1,2,3};
List arr3=Arrays.asList(intarr);
System.out.println(arr3);//[[I@1540e19d]
//而对于String来讲,他是一个对象,所以可以
String [] stringarr =new String[]{"e","f"};
List arr4=Arrays.asList(stringarr);
System.out.println(arr4);//[e,f]
//1.3 Arrays.asList()返回一个受指定数组支持的固定大小的集合。所以不能做Add、Remove等操作。
// arr4.add(11111111);//报错java.lang.UnsupportedOperationException,改成如下
List arr5 = new ArrayList(arr4);
arr5.add(11111111);
System.out.println(arr5);//[e, f, 11111111]
//System.out.println(arr5.get(1));
//2.集合转数组
List arr6= Arrays.asList(1,2,3);
Object [] obj=arr6.toArray();//返回的是Object数组
System.out.println(obj[1]);//2
//2.1可以使用强转符,改变Object类型
//String [] strarr2 = (String[])obj;//根据arr6可看obj里存的是Integer的对象,所以只能转化成下面的
Integer [] intarr2 = (Integer[])obj;
System.out.println(intarr2[1]);//2
//3.遍历
//3.1集合
List arr7=Arrays.asList(1,"a","ccc");
Iterator iterator = arr7.iterator();//调用List集合的iterator方法,返回迭代器
while (iterator.hasNext()){
System.out.println(iterator.next());
}
//3.2数组
int [] arr8=new int[]{1,2,3,4};
for(int i =0;i<arr8.length;i++){
System.out.println(arr8[i]);
}
}
}