zoukankan      html  css  js  c++  java
  • Integer 类型比较大小

    == 比较 Integer 大小

    Integer n1 = 127;
    Integer n2 = 127;
    System.out.println(n1 == n2);       // true
    System.out.println(n1.equals(n2));  // true
    
    Integer n1 = 128;
    Integer n2 = 128;
    System.out.println(n1 == n2);       // false
    System.out.println(n1.equals(n2));  // true
    

    首先Integer n1 = 127; 这种赋值方式,是会进行装箱操作的;
    下面我们看一下源码

    public static Integer valueOf(int i) {
            if (i >= IntegerCache.low && i <= IntegerCache.high)
                return IntegerCache.cache[i + (-IntegerCache.low)];
            return new Integer(i);
        }
    
    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() {}
        }
    

    本质是因为 Integer 内部维护了一个IntegerCache,
    -128 到 127 是byte的取值范围,如果在这个取值范围内,自动装箱就不会创建对象,而是从常量池中获取,如果超过了byte的取值返回就会再新创建对象;

  • 相关阅读:
    leetcode 6 ZigZag Conversion
    OpenCL异构计算资料收集
    leetcode 21 Merge Two Sorted Lists
    leetcode 226 Invert Binary Tree 翻转二叉树
    leetcode 8 String to Integer (atoi)
    leetcode 27 Remove Element
    【Office】add ins
    【office】deploy
    【Office】add ins manifest
    【设计】交互设计理念
  • 原文地址:https://www.cnblogs.com/Godfunc/p/9195533.html
Copyright © 2011-2022 走看看