三、Java提升之基本数据类型(int)与包装器类型(Integer)

##一.定义与区别

int 属于基本数据类型
Integer属于对int基本数据类型进行封装的包装器类

基本数据类型包装器类
int(4字节)Integer
byte(1字节)Byte
short(2字节)Short
long(8字节)Long
float(4字节)Float
double(8字节)Double
char(2字节)Character
boolean(未定)Boolean

##二、JavaSE5的装箱和拆箱特性

生成一个Integer的数值对象:
Java SE5之前:Integer i = new Integer(1);
Java SE5之后:Integer i = 1; //装箱
Java SE5之后:int n = i; //拆箱
装箱:将基本数据类型装换为包装器类型;
拆箱:自动将包装器类型转换为基本数据类型;

##三、装箱和拆箱如何实现?
示例代码:

package com.person.dataType;

public class IntegerTest {
	public static Integer integer_1 = new Integer(10);
	
	public static int getInt(String string){
		return Integer.valueOf(string);
	}
	
	public static void main(String[] args) {
		Integer i = 10; //Boxed
		int n = i;	//unpacked
		System.out.println(integer_1);
		System.out.println(getInt("123456"));
	}
}

通过javac对IntegerTest.java文件进行编译后,在通过javap对class文件进行反编译

C:\Users\***\Desktop>javap -c IntegerTest
警告: 二进制文件IntegerTest包含com.person.dataType.IntegerTest
Compiled from "IntegerTest.java"
public class com.person.dataType.IntegerTest {
  public static java.lang.Integer integer_1;

  static {};
    Code:
       0: new           #10                 // class java/lang/Integer
       3: dup
       4: bipush        10
       6: invokespecial #12                 // Method java/lang/Integer."<init>":(I)V
       9: putstatic     #16                 // Field integer_1:Ljava/lang/Integer;
      12: return

  public com.person.dataType.IntegerTest();
    Code:
       0: aload_0
       1: invokespecial #20                 // Method java/lang/Object."<init>":()V
       4: return

  public static int getInt(java.lang.String);
    Code:
       0: aload_0
       1: invokestatic  #26                 // Method java/lang/Integer.valueOf:(Ljava/lang/String;)Ljava/lang/Integer;
       4: invokevirtual #30                 // Method java/lang/Integer.intValue:()I
       7: ireturn

  public static void main(java.lang.String[]);
    Code:
       0: bipush        10
       2: invokestatic  #38                 // Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;
       5: astore_1
       6: aload_1
       7: invokevirtual #30                 // Method java/lang/Integer.intValue:()I
      10: istore_2
      11: getstatic     #41                 // Field java/lang/System.out:Ljava/io/PrintStream;
      14: getstatic     #16                 // Field integer_1:Ljava/lang/Integer;
      17: invokevirtual #47                 // Method java/io/PrintStream.println:(Ljava/lang/Object;)V
      20: getstatic     #41                 // Field java/lang/System.out:Ljava/io/PrintStream;
      23: ldc           #53                 // String 123456
      25: invokestatic  #55                 // Method getInt:(Ljava/lang/String;)I
      28: invokevirtual #57                 // Method java/io/PrintStream.println:(I)V
      31: return
}

解析:
#12:调用了Integer的有参构造函数
#20:隐式的将Object超类加载进去了
#26:在getInt()方法体内调用了Integer.valueOf进行装箱
#30:在getInt()方法体内调用了Integer.intValue进行拆箱
#38:是对基本数据类型值10进行装箱操作


Integer的源码中有一个特殊的内部类是用来提前将[-127,127]区间的数字进行实例化

    /**
  * 缓存支持自动装箱的对象标识语义
  * -128和127(含)。
  *
  * 缓存在第一次使用时初始化。 缓存的大小
  * 可以由-XX:AutoBoxCacheMax = <size>选项控制。
  * 在VM初始化期间,java.lang.Integer.IntegerCache.high属性
  * 可以设置并保存在私有系统属性中
 */
private static class IntegerCache {
        static final int low = -128;
        static final int high;
        static final Integer cache[];

        static {
            // high value may be configured by property
            int h = 127;
            String integerCacheHighPropValue =
                sun.misc.VM.getSavedProperty("java.lang.Integer.IntegerCache.high");
            if (integerCacheHighPropValue != null) {
                try {
                    int i = parseInt(integerCacheHighPropValue);
                    i = Math.max(i, 127);
                    // Maximum array size is Integer.MAX_VALUE
                    h = Math.min(i, Integer.MAX_VALUE - (-low) -1);
                } catch( NumberFormatException nfe) {
                    // If the property cannot be parsed into an int, ignore it.
                }
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++)
                cache[k] = new Integer(j++);

            // range [-128, 127] must be interned (JLS7 5.1.7)
            assert IntegerCache.high >= 127;
        }

        private IntegerCache() {}
    }

为什么需要将这一部分数段提前进行实例化? 譬如淘宝中,大部分商品的价格都是100以下,下单最多的商品单价也是100以内,那么用户每下单一次就需要new一个对象,一天下来得new多少对象?用户量级那么大,想想就觉得恐怖,那么提前将这一少部分对象提前实例化,并且设置为static final,让这部分对象在程序运行期间一直存在,那么就可以大大减少用户下单商品时新建的对象数量。
为什么要提到上面那段代码?下面我们来看源码中隐式装箱需要调用的方法,只有当数值不在[IntegerCache.low, IntegerCache.high]区间内才会new Integer(i)对象,否则直接返回内存中的对象。

public static Integer valueOf(int i) {
        if (i >= IntegerCache.low && i <= IntegerCache.high)
            return IntegerCache.cache[i + (-IntegerCache.low)];
        return new Integer(i);
}

看了上面的源码之后就会引出一个面试中常见的问题:

public static void main(String[] args) {
		Integer i = 100;
		Integer j = 100;
		Integer o = 200;
		Integer p = 200;
		System.out.println((i == j) +" and "+(o == p));
}

显示结果显而易见:

true and false

####后话1:

什么时候定义变量的时候用Integer而不用int?
定义该变量涉及到数据库交互的时候,因为数据库中如果有个字段没有值可能默认为null,而Integer允许为null值,int默认为0.


####后话2:new Integer()和Integer.valueOf()效率的比较

Integer i = new Integer(intDate)和Integer i =intData的区别为前一种不会触发自动装箱,后一种会触发,并且第二种方式的执行效率和资源占用一般情况下要优于第一种,为什么?
后一种触发自动装箱的实质是调用了Integer.valueOf(),因此可看成是new Integer()和Integer.valueOf()效率的比较,上面已经很详细的说了,当数字在[-127,127]的区间的时候会利用到IntegerCache直接返回同一地址的数字,但是new Integer()返回的永远都是不同的对象

public static void main(String[] args) {
	Integer i1 = new Integer(1);
	Integer i2 = new Integer(1);
	Integer i3 = 1;
	Integer i4 = 1;
	int n1 = 1;
	System.out.println(i2 == i3);
	System.out.println(i1 == n1);
	System.out.println(i2 == n1);
	System.out.println(i2 == i1);
	System.out.println();	
}

显示结果:

false
true
true
false

上面的结论例子足够引起我们的思考,设置断点通过debug后显示的结果

args	String[0]  (id=17)	
i1	    Integer  (id=19)	
i2	    Integer  (id=25)	
i3	    Integer  (id=26)	
i4	    Integer  (id=26)	
n1	    1	

我们发现,i1和i2的id不同,也就是对象不同;i3和i4对象相同,n1并没有id标号,综上所述得出的结论:
实际上i1和i2通过“”变量比较的是引用对象的地址,比较的是引用对象的地址,那肯定不相等啊,因为是两个不同的对象,所以两个不同的对象地址下保存的着相同的地址指向同一个值。""用来比较的是地址,equal用来比较的是同一类型对象的地址下的两个值是否相等,与地址无关。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值