Java int和Integer 的区别

今天突然想到之前面试的时候的一个面试题,上来面试官就问我,int和Integer 有什么区别?
  • 马上我脱口而出: int 基本数据类型, Integer 是int的包装类型

  • 然后面试官继续问:还有什么区别?(我不知道面试官想我说什么…)

  • 于是又说:int的默认值是0 Integer 的默认值是null

  • 面试官还继续问:还有什么区别(当时就在想,我他吗,这个问吃饭用筷子有啥区别…走路用腿有啥区别)

  • 大脑飞速旋转还有啥区别:Integer 变量必须实例化后才能使用,int就不需要实例化使用啊

面试官衣服趾高气昂的样子,我他吗,内伤复发,现在面试就怕遇到这样的面试官,后面面试就没啥心思,你问我答,敷衍结束…

后来我在想,一个优秀的面试者,遇到这种事情都是能反客为主,还是自己学的不够深入,没有自己去注意平时的这些细节,所以现在对这个面试问题总结一下;

int 和 Integer 有啥区别

1.Integer 是int包装类的包装类,int是基本数据类型
2.Integer 变量必须实例化后才能使用,int变量不需要
3.Integer 实例的是对象的引用,指向的是new 的 Integer 对象,int是直接存储数据值
4.Integer 的默认值是null int的默认值是0

int 和Integer 深入浅出对比

1.由于Integer变量实际上是对一个Integer对象的引用,所以两个通过new生成的Integer变量永恒不相等(因为new生成的是两个对象,其内存地址不同).

Integer i = new Integer(100);
Integer j = new Integer(100);
System.out.print(i == j); //false

2.Integer变量和int变量比较时只是两个变量值是相等的,则结果为true(因此包装类Integer 和基本数据类型相比,java会自动拆包装int,然后进行比较,实际上就是变为两个int变量比较)

Integer i = new Integer(100);
int j = 100;
System.out.print(i == j); //true

3.非new生成的Integer变量和new Integer()生成的变量比较时,结果为false。因为非new生成的Integer变量指向的是静态常量池中cache数组中存储的指向了堆中的Integer对象,而new Integer()生成的变量指向堆中新建的对象,两者在内存中的对象引用(地址)不同

Integer i = new Integer(100);
Integer j = 100;
System.out.print(i == j); //false

4.对于两个非new生成的Integer对象,进行比较时,如果两个变量的值在区间-128到127之间,则比较结果为true,如果两个变量的值不在此区间,则比较结果为false

Integer i = 100;
Integer j = 100;
System.out.print(i == j); //true

Integer i = 128;
Integer j = 128;
System.out.print(i == j); //false

对于第4条的原因: java在编译Integer i = 100 ;时,会翻译成为Integer i = Integer.valueOf(100)。而java API中对Integer类型的valueOf的定义如下,对于-128到127之间的数,会进行缓存,Integer i = 127时,会将127这个Integer对象进行缓存,下次再写Integer j = 127时,就会直接从缓存中取,就不会new了。

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

自动装箱和自动拆箱

自动装箱:将基本数据类型重新转化为对象
    public class Test {  
        public static void main(String[] args) {  
            // 声明一个Integer对象,用到了自动的装箱:解析为:Integer num = Integer.valueOf(9);
	        Integer num = 9;
        }  
    }  

9是属于基本数据类型的,原则上它是不能直接赋值给一个对象Integer的。但jdk1.5后你就可以进行这样的声明,自动将基本数据类型转化为对应的封装类型,成为一个对象以后就可以调用对象所声明的所有的方法。

自动拆箱:将对象重新转化为基本数据类型

 public class Test {  
        public static void main(String[] args) {  
            / /声明一个Integer对象
	        Integer num = 9;
            
            // 进行计算时隐含的有自动拆箱
		    System.out.print(num--);
        }  
    }  

因为对象时不能直接进行运算的,而是要转化为基本数据类型后才能进行加减乘除。对比

// 装箱
Integer num = 10;
// 拆箱
int num1 = num;

深入解析Integer

问题描述

   public class Test {  
        public static void main(String[] args) {  
	        // 在-128~127 之外的数
            Integer num1 = 128;   
            Integer num2 = 128;           
            System.out.println(num1==num2);   //false
                        
            // 在-128~127 之内的数 
            Integer num3 = 9;   
            Integer num4 = 9;   
            System.out.println(num3==num4);   //true
        }  
    }  

解析原因:归结于java对于Integer与int的自动装箱与拆箱的设计,是一种模式:叫享元模式
(1)加大对简单数字的重利用,Java定义在自动装箱时对于在-128~127之内的数值,它们被装箱为Integer对象后,会存在内存中被重用,始终只存在一个对象。
(2)而如果在-128~127之外的数,被装箱后的Integer对象并不会被重用,即相当于每次装箱时都新建一个 Integer对象。

Integer源码解析

给一个Integer对象赋一个int值的时候,会调用Integer类的静态方法valueOf,源码如下:

public static Integer valueOf(String s, int radix) throws NumberFormatException {
        return Integer.valueOf(parseInt(s,radix));
    }


/**
 * (1)在-128~127之内:静态常量池中cache数组是static final类型,cache数组对象会被存储于静态常量池中。
 * cache数组里面的元素却不是static final类型,而是cache[k] = new Integer(j++),
 * 那么这些元素是存储于堆中,只是cache数组对象存储的是指向了堆中的Integer对象(引用地址)
 * 
 * (2)在-128~127 之外:新建一个 Integer对象,并返回。
 */
public static Integer valueOf(int i) {
        assert IntegerCache.high >= 127;
        if (i >= IntegerCache.low && i <= IntegerCache.high) {
            return IntegerCache.cache[i + (-IntegerCache.low)];
        }
        return new Integer(i);
    }

IntegerCache是Integer的内部类,源码如下:

     /**
      * 缓存支持自动装箱的对象标识语义 -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) {
                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);
            }
            high = h;

            cache = new Integer[(high - low) + 1];
            int j = low;
            for(int k = 0; k < cache.length; k++) {
                cache[k] = new Integer(j++); // 创建一个对象
            }
        }

        private IntegerCache() {}
    }

转载于:https://blog.csdn.net/chenliguan/article/details/53888018

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值