【Java】Java中Integer和int比较大小出现的错误

来源:互联网 发布:淘宝客服忙吗 编辑:程序博客网 时间:2024/06/05 18:00

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

范围在 -128 ~ 127 之间(包括),直接用==

Integer i = 100;int j = 100;return i == j;//true

这里返回的是true.

但是 >127 或者 <-128

Integer i = 500;int j = 500;return i == j; //false

所以当需要判断的Integer不在这个范围的时候,最好用parseInt()方法转换成int后再去比较大小