Java中的Boxing和AutoBoxing有什么区别?

Java中的Boxing和AutoBoxing有什么区别?一些Java认证书使用了两个这样的术语.他们是指与Boxing相同的东西吗?

解决方法

拳击是机制(即从int到Integer); autoBoxing是编译器的功能,通过它可以为您生成装箱代码.

例如,如果你写代码

// list is a List<Integer>
list.add(3);

然后编译器会自动为您生成装箱代码;代码中的“最终结果”将是:

list.add(Integer.valueOf(3));

关于为什么Integer.valueOf()而不是新的Integer()的说明:基本上,因为JLS这么说:)引用section 5.1.7

If the value p being Boxed is true,false,a byte,or a char in the
range \u0000 to \u007f,or an int or short number between -128 and 127
(inclusive)
,then let r1 and r2 be the results of any two Boxing
conversions of p. It is always the case that r1 == r2.

如果您使用“仅仅”构造函数,则无法强制执行此要求.工厂方法,如Integer.valueOf(),可以.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...