Java中自动包装机制与数组

基本类型的数组与包装类型的数组之间转换时会在编译时报错

在Java中自动包装机制不能作用于数组,当用基本类型的数组与包装类型的数组进行相互赋值时会报异常(Type mismatch: cannot convert from int[] to Integer[]
例如:
在这里插入图片描述
例子代码如下:

public class Demo1 {
	public static void main(String[] args) {
		int[] pa = { 1, 2, 3, 4, 5 };
		Integer[] wa = pa;//Type mismatch: cannot convert from int[] to Integer[]
		Integer[] wb = { 1, 2, 3, 4, 5 };
		int[] pb = wb;//Type mismatch: cannot convert from Integer[] to int[]
	}
}

基本类型数组与包装类型数组之间的转换

因为基本类型的数组与包装类型之间的数组之间不能互相转换,因此只能通过遍历的形式,使的单个的基本类型与包装类型之间能正常的进行自动装箱(Autoboxing)自动拆箱(Autounboxing)

import java.util.Arrays;
public class Demo1 {
	public static void main(String[] args) {
		int[] pa1 = { 1, 2, 3, 4, 5 };
		Integer[] wa1=convert(pa1);
		System.out.println("int[]-->Integer[]:"+Arrays.toString(wa1));
		
		Integer[] wa2 = { 1, 2, 3, 4, 5 };
		int[] pa2=convert(wa2);
		System.out.println("Integer[]-->int[]:"+Arrays.toString(pa2));
	}
	//Integer[]-->int[]
	public static int[] convert(Integer[] wa) {
		int[] pa = new int[wa.length];
		for (int i = 0; i < wa.length; i++) {
			pa[i] = wa[i];//Autounboxing
		}
		return pa;
	}
	//int[]-->Integer[]
	public static Integer[] convert(int[] pa) {
		Integer[] wa = new Integer[pa.length];
		for (int i = 0; i < pa.length; i++) {
			wa[i] = pa[i];//Autoboxing
		}
		return wa;
	}
}

输出
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值