自动装箱、拆箱与遍历循环在java语言里是使用最多的语法糖。

通过反编译之后的代码如下:
publicstaticvoidmain(String[] args) {
List list = Arrays.asList(newInteger[] {null,null,null, (newInteger[4][2] = (newInteger[4][1] = (newInteger[4][0] = Integer.valueOf(1)).valueOf(2)).valueOf(3)).valueOf(4) });
intsum = 0;
for(Iterator iterator = list.iterator(); iterator.hasNext(); ) {inti = ((Integer)iterator.next()).intValue();
sum += i; }
System.out.println(sum);
}
如上,自动装箱、拆箱在编译之后被转化成了对应的包装和还原方法,而遍历循环则把代码还原成了迭代器实现,这也是为何遍历循环需要被遍历的类实现Iterable接口的原因。
自动装箱的陷阱,

上面代码输出:

反编译代码如下:

我们看到在只有“==”运算的时候是不会做自动拆箱处理的,而如果有算数运算则会进行自动拆箱。同时equals()方法不处理数据类转型的关系。
网友评论