Integer比较

来源:互联网 发布:路由器mac地址什么意思 编辑:程序博客网 时间:2024/05/02 23:33
/** * @time 2014-06-25 * @author Cao HaiCheng * */public class demo {public static void main(String[] args) {test1();test2();test3();test4();test5();}/** * 第一个答案是false很好理解,因为'=='操作符比较的是两个对象的地址,a和b指向的地址不同 */private static void test1() {    Integer a = new Integer(50);      Integer b = 50;      System.out.println("test1运行结果:"+(a == b));   //false}/** * 这个答案是true,Integer a=50属于自动装箱,调用的是编译器中的public static Integer valueOf(int i)方法 * 我们看下这个方法: *     public static Integer valueOf(int i) {        assert IntegerCache.high >= 127;        if (i >= IntegerCache.low && i <= IntegerCache.high)            return IntegerCache.cache[i + (-IntegerCache.low)];        return new Integer(i);      } *  * 我们可以看到jdk源码中定义的这个方法意思是这样的:当i的值在某个范围之间的时候不用创建对象,直接去IntegerCache中取,再看下这个 * IntegerCache类: *     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) {                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);            }            high = h;            cache = new Integer[(high - low) + 1];            int j = low;            for(int k = 0; k < cache.length; k++)                cache[k] = new Integer(j++);        }        private IntegerCache() {}      } * 我们看到这个Cache里面放了256个值,就是-128到127之间的值 * 所以当Integer a = 50;  的时候并没有创建新的对象,还是引用的缓存池中的地址,所以这个结果为true */private static void test2() {   Integer a = 50;     Integer b = 50;     System.out.println("test2运行结果:"+(a == b)); //true }/** * 这个根据上面那个说法就简单了,因为150并不在-128到127之间,所以这个需要自己创建对象,创建的对象a和b的指向地址不同 * 所以该结果为false; */private static void test3() {    Integer a = 150;      Integer b = 150;      System.out.println("test3运行结果:"+(a == b));//false  }/** * 这个 Integer a = Integer.valueOf(50); 和Integer b = 50;  调用的方法都是编译器中的public static Integer valueOf(int i)方法 * 所以两个50都没有创建新的对象,都是从缓存池中拿到的对象,所以结果为true */private static void test4() {    Integer a = Integer.valueOf(50);      Integer b = 50;      System.out.println("test4运行结果:"+(a == b));   //true}/** * 同理,数值超出了范围,所以指向不同,结果为false */private static void test5() {    Integer a = Integer.valueOf(150);      Integer b = 150;      System.out.println("test5运行结果:"+(a == b));  //false}}

1 0
原创粉丝点击