自动装箱,自动拆箱,遍历循环(Foreach)是程序设计过程中使用最多的语法糖
案例:
自动装箱,拆箱,遍历循环
public class ForeachTest {
public static void main(String[] args) {
List<Integer> list=Arrays.asList(1,2,3,4);
int sum=0;
for(int i:list)
{
sum+=i;
}
System.out.println(sum);
}
}
编译之后反编译,擦除语法糖后
public class ForeachTest {
public static void main(String[] args) {
List list=Arrays.asList(
new Integer[]
{
Integer.valueOf(1);
Integer.valueOf(2);
Integer.valueOf(3);
Integer.valueOf(4);
};
);
int sum=0;
for(Iterator<E> localIterator=list.iterator();localIterator.hasNext();)
{
int i=((Integer)localIterator.next()).intValue();
sum+=i;
}
System.out.println(sum);
}
}
通过Integer.valueof()与Integer.intValue()方法完成对应的自动装箱拆箱,通过Iterable接口完成Foreach的遍历
自动拆箱,装箱案例:
public static void main(String[] args) {
Integer a=1;
Integer b=2;
Integer c=3;
Integer d=3;
Integer e=321;
Integer f=321;
Long g=3L;
System.out.println(c==d);
System.out.println(e==f);
System.out.println(c==(a+b));
System.out.println(c.equals(a+b));
System.out.println(g==(a+b));
System.out.println(g.equals(a+b));
}
运行结果:
- 对于Integer当整型的值在区间 [-128,127] 之间时,所对应的对象都是方法区常量池的同一个对象
- 而在这之外区间之外的数值,则会创建新的Integer对象,
其设计的目的是该区间的整形数值最经常被使用,采用池化设计减少对象的频繁创建和回收