【Java】Java中Integer和int比较大小出现的错误
2017-06-15 14:55
417 查看
Java的Integer类有一个内部类,缓存着一个常量池.
这里返回的是true.
所以当需要判断的Integer不在这个范围的时候,最好用parseInt()方法转换成int后再去比较大小
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后再去比较大小
相关文章推荐
- java Integer.ValueOf(int)和new Integer(int)性能比较
- java Integer和int之间==的比较问题
- Java中int和Integer关系比较
- java Integer和int之间==的比较问题 equal
- Java进阶(三十四)Integer与int的种种比较你知道多少?
- java Integer和int之间==的比较问题。求解释
- Java 小例子:不通过逻辑运算和类库,比较两个 integer 大小
- Java中的Integer和int等包装类和基本数据类型简单比较
- JAVA中Long与Integer比较容易犯的错误
- Java中int和Integer关系是比较微妙的
- java Integer和int之间==的比较问题。求解释
- java中Integer与int的种种比较你知道多少?
- Java中Integer直接比较大小
- JAVA中Long与Integer比较容易犯的错误
- java Integer.ValueOf(int)和new Integer(int)性能比较
- java foreach循环遍历List 如何比较List里面值的大小 里面值是int
- Java Integer和int类型变量的两两相等性比较
- Java int 同步和原子AtomicInteger效率比较
- java中Integer,String判断相等与integer的比较大小
- Java进阶(三十四)Integer与int的种种比较你知道多少?