Java中int与integer的区别

Java中int与integer的区别

  1. int是基本数据类型,数据直接存放在Java的栈中。
  2. Integer是引用数据类型,是int的封装类,Integer变量必须实例化后才能使用,里面封装了对整型数据操作的封装。
  3. Integer的默认值是null,int的默认值是0

  1. 由于Integer变量实际上是对一个Integer对象的引用,所以两个通过new生成的Integer变量永远是不相等的(因为new生成的是两个对象,其内存地址不同)。
Integer i = new Integer(100);
Integer j = new Integer(100);
System.out.print(i == j); //false

Java

Copy

  1. Integer变量和int变量比较时,只要两个变量的值是向等的,则结果为true(因为包装类Integer和基本数据类型int比较时,java会自动拆包装为int,然后进行比较,实际上就变为两个int变量的比较)
Integer i = new Integer(100);
int j = 100;
System.out.print(i == j); //true

Java

Copy

  1. 非new生成的Integer变量和new Integer()生成的变量比较时,结果为false。(因为非new生成的Integer变量指向的是java常量池中的对象,而new Integer()生成的变量指向堆中新建的对象,两者在内存中的地址不同)
Integer i = new Integer(100);
Integer j = 100; //自动装箱
System.out.print(i == j); //false

Java

Copy

  1. 对于两个非new生成的Integer对象,进行比较时,如果两个变量的值在区间-128到127之间,则比较结果为true,如果两个变量的值不在此区间,则比较结果为false
Integer i = 100;
Integer j = 100;
System.out.print(i == j); //true

Java

Copy


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

Java

Copy

出现以上的原因是因为当我们给一个Integer对象赋一个int值的时候,会调用Integer类的静态方法valueOf,我们看一看valueOf方法就知道为什么会有这样的结果了。
blob.jpg
– 从上面的代码中我们可以看出Integer维持了一个缓存系统,如果在缓存的范围内直接取出来就好了,如果不在的就要创建新的Integer对象。但是具体缓存范围是什么的,我们在深入进去看看:

 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() {}
    }

Java

Copy

看完之后我相信基本都知道为啥一开始的那一段代码会这样了,我现在做一个小的总结,Integer里面有一个内部类IntegerCache,是用来做缓存优化性能的。默认缓存了-128到127中间的数字,据说这些使的比较频繁。其实java里面好多的类都有这样的优化。如果在-128-127之间的就直接拿缓存的,不在的就new一个Integer。所以这也就解释了上面的那个问题了嘛

原文地址:https://www.cnblogs.com/cuianbing/p/14475136.html