java基本语法-装箱转换和拆箱转换

来源:互联网 发布:深圳蜂窝网络是培训 编辑:程序博客网 时间:2024/06/03 14:19

情形1:将基本类型的值传递给一个方法,而这个方法需要参数是一格指向对象的引用;从基本类型转换为类,称为装箱

情形2:对于封装基本类型的类,需要指向对象的引用转换为封装的值,称为拆箱;

package test;

/**

 * @author Clark

 * 装箱:Integer i = 100; (注意:不是 int i = 100; )

 * 实际上,执行上面那句代码的时候,系统为我们执行了:Integer i = Integer.valueOf(100);

 * 拆箱:int t = i; //拆箱,实际上执行了int t = i.intValue();

 */

public class AutoboxingInAction {

public static void main(String[]args){

int[] values={3,97,55,22,12345};

//Array to store Integer Objects

Integer[] objs=new Integer[values.length];

//call method to cause boxing conversions

for(int i=0;i<values.length;++i){

objs[i]=boxInteger(values[i]);

}

//calll method tounboxing

 for (Object obj : objs) {

 unboxInteger((Integer) obj);

  }

}

//Method to cause boxing conversion

public static Integer boxInteger(int obj) {

return Integer.valueOf(obj);

}

//Method to cause unboxing conversion

public static void unboxInteger(Integern) {

System.out.println("元素"+n.intValue());

}

}

 

**************************************************************** 欢迎转发,注明原文:blog.csdn.net/clark_xu   徐长亮的专栏** 谢谢您的支持,欢迎关注微信公众号:clark_blog **************************************************************

0 0
原创粉丝点击