JAVA 关于自动包装与拆包的理解

  • Post author:
  • Post category:java


转自

https://www.cnblogs.com/wang-yaz/p/8516151.html

Ingeter是int的包装类。

int的初值为0。

Ingeter的初值为null。

//声明一个Integer对象
Integer num = 10;
//以上的声明就是用到了自动的装箱:解析为
Integer num= Integer.valueOf(10);

int n= num; 
执行上面那句代码的时候,系统为我们执行了拆箱: 
int n= num.intValue();

1、

装箱:

Integer.valueOf函数

private static final Integer[] SMALL_VALUES = new Integer[256]; 

public static Integer valueOf(int i) {
return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];
}

它会首先判断i的大小:如果i小于-128或者大于等于128,就创建一个Integer对象,否则返回一个已经存在的Integer数组一个位置的引用:SMALL_VALUES[i + 128],它是一个静态的Integer数组对象,其中存储了-127到128。可以看出,在-127到128之间的使用自动装箱产生的Integer对象都不会产生新的Integer对象,并且在这个范围内值相同的Integer对象的引用也相同。

然后我们来看看Integer的构造函数:

1 private final int value;
2 
3 public Integer(int value) {
4     this.value = value;
5 }
6 
7 public Integer(String string) throws NumberFormatException {
8     this(parseInt(string));
9 }

它里面定义了一个value变量,创建一个Integer对象,就会给这个变量初始化。第二个传入的是一个String变量,它会先把它转换成一个int值,然后进行初始化。

2、

拆箱:

intValue函数

1 @Override
2 public int intValue() {
3     return value;
4 }

这个很简单,直接返回value值即可。

一般进行数值计算或者使用到Integer对象的值得时候,需要自动拆包