Integer自动装箱分析

先看看下面的代码会输出什么:

public static void main(String[] args) {

Integer i = 127;

Integer j = 128;

Integer ii = 127;

Integer jj = 128;

System.out.println( i==ii );

System.out.println( j==jj );

}

答案是:true,false

这是为什么呢?原因在于装箱动作是通过valueOf方法实现的,

在valueOf方法中采用了对象池。如果参数在-128~127之间,则

直接从对象池中获得对象,不在该范围之内的才通过new生成包装对象。

我们来看看源代码:

public static Integer valueOf(int i) {

assert IntegerCache.high >= 127;

if (i >= IntegerCache.low && i <= IntegerCache.high)

//low=-128,high=127

return IntegerCache.cache[i + (-IntegerCache.low)];

return new Integer(i);

}

那么装箱的动作为什么看不到呢?你怎么知道一定是调用valueOf函数呢?

自动装箱是编译其行为。我们可以将代码编译后再进行反编译,看看JVM指令是什么。

下面是上面例子中反编译出来的部分代码:

Compiled from "IntegerTest.java"

public class Test.IntegerTest {

public Test.IntegerTest();

Code:

0: aload_0

1: invokespecial #1 // Method java/lang/Object."<init>":()V

4: return

public static void main(java.lang.String[]);

Code:

0: bipush 127

2: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;

5: astore_1

6: sipush 128

9: invokestatic #2 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;

}

我们可以看到自动装箱确实是调用valueOf函数

原文地址:https://www.cnblogs.com/downey/p/4946823.html