list转为Integer[]:通过List的toArray()方法转换,具体见下面代码
list转为int[]:1、通过list的toArray()方法转成Integer[]型再一个个转成int[]型;2、直接从list中读出来,一个一个转成int[]型
Integer[]转为int[]:一个一个转
int[]转为Integer[]:一个一个转
public class InTest {
public static void main(String[] args) {
/*将list转化为Integer[]*/
ArrayList<Integer> intList = new ArrayList<Integer>();//泛型为Integer
intList.add(123);
intList.add(456);
intList.add(789);
Integer[] b = new Integer[intList.size()];//当泛型为Integer时,需要以
b = (Integer[])intList.toArray(b); //Integer类来作为数组基本元素
System.out.println(Arrays.toString(b));//,否则输出会报错。
/*强制转换为Integer[]*/
try{
Integer[] c = (Integer[])intList.toArray(); //此处编译没问题,但是,
System.out.println(Arrays.toString(c)); //泛型向下转换运行会出错
}catch(Exception e){
System.out.println("捕获到异常");
}
/*循环的方法把list<Integer>型数组转换成int[]数组,只能一个一个转换*/
int[] d = new int[intList.size()];
for(int i = 0;i<intList.size();i++){
d[i] = intList.get(i);
}
System.out.println( Arrays.toString(d));
/*把Integer型转换成int型*/
Integer a1 = new Integer(10);
int a2 = a1;
System.out.println(a2);
/*把Integer[]型数组转换成int[]只能一个一个转换*/
int[] a4 = new int[3];
Integer[] a3 = new Integer[]{1, 2, 3};
for(int i =0; i<a3.length; i++){
a4[i] = a3[i].intValue();
}
System.out.println(Arrays.toString(a4));
/*把int型转换成Integer型*/
int b1 = 30;
Integer b2 = b1;
System.out.println(b2);
/*把int[]型转换成Integer[]型,则也需要一个一个的转换*/
int[] b3 = new int[]{1,2,3};
Integer[] b4 = new Integer[3];
for(int i =0; i<b3.length; i++){
b4[i] = b3[i];
}
System.out.println(Arrays.toString(b4));
}
}