JAVA两个Integer 中1000==1000为false而100==100为true?

xiaoxiao2021-02-27  166

这个问题刚遇见的时候很是奇怪,先贴上测试代码

public class SOlution { public static void main(String[] args){ Integer a=1000; Integer b=1000;    System.out.println(a==b);    Integer a1=100; Integer b1=100;    System.out.println(a1==b1); } }

测试结果:

false;

true;

很是傻眼,不信你去试试;理论上来说两个Integer类用“==”比较的话怎么也应该是false,怎么到了100就变成true了呢?

原因解析:需要查看java中Integer中的源代码(见下方)。下面源代码中标红的代码段是重点。Integer类中有个内部类:IntegerCache ,这个类中有一个缓存数组cache[],存放的内容是-128到127的整数(看蓝色代码)。最后再看Integer类中的valueOf()方法,在-128到127之间的数之间返回cache数组中的Integer,否则新建一个Integer类,本质就在这,这就解释了为什么a1和b1两个integer引用地址是一样的了,因为他们根本就是同一个实例。而a和b是两个不同的Integer实例

JAVA 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() {}     }     /**      * Returns an {@code Integer} instance representing the specified      * {@code int} value.  If a new {@code Integer} instance is not      * required, this method should generally be used in preference to      * the constructor {@link #Integer(int)}, as this method is likely      * to yield significantly better space and time performance by      * caching frequently requested values.      *      * This method will always cache values in the range -128 to 127,      * inclusive, and may cache other values outside of this range.      *      * @param  i an {@code int} value.      * @return an {@code Integer} instance representing {@code i}.      * @since  1.5      */     public static Integer valueOf(int i) {         if (i >= IntegerCache.low && i <= IntegerCache.high)             return IntegerCache.cache[i + (-IntegerCache.low)];         return new Integer(i);     }

转载请注明原文地址: https://www.6miu.com/read-13304.html

最新回复(0)