【Java基础】list转为Integer[]、list转为int[]、Integer[]转为int[]、int[]转为Integer[]

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));
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值