8 int和Integer的区别

数据类型

int是基本数据类型,Integer是int的包装类,属于引用类型

初始值

int的初始值为0,Integer的初始值为null

存储位置

int是直接存储在栈中的,Integer是引用数据类型,存储在栈中的是它的内存地址,实际的对象存储在堆中

比较

int比较的是两个变量的值是否相等,Integer比较的是内存地址是否相同

传递方式

int在传递参数时都是按值传递,Integer按引用传递,传递的是对象的内存地址


 衍生一下:自动装箱/自动拆箱

从Java5开始引入了自动装箱/自动拆箱机制,二者可以相互转换

public class T {
    public static void main(String[] args) {
        //自动装箱
        Integer a = 10;
        //自动拆箱
        int b = a;
    }
}

自动装箱:就是自动将基本数据类型转换为引用类型

自动拆箱:就是自动将引用类型转换为基本数据类型

自动装箱实现原理

当我们给一个Integer对象赋一个int值时,会调用Integer类的valueOf()方法,通过阅读源码,我们可以得到这样的结论:如果整数的值在-128~127之间,就不会new新的Integer对象,而是直接引用常量池中的Integer对象,如果不在这个范围内,则会new新的Integer对象。

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

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);
}    

注意:除了double和float没有使用缓存,其它6种基本数据类型都使用了缓存策略

自动拆箱实现原理

当我们给一个int变量赋一个Integer对象时,其实调用的时Integer.intValue()方法,这个很简单,直接返回value值。

public int intValue() {
  return value;
}
posted @ 2020-12-17 15:56  卫盾  阅读(234)  评论(0编辑  收藏  举报