日期:2014-05-20  浏览次数:20880 次

隔壁帖子看地题目,谁能给解释一下结果?
Java code
package com.dhcc.yang;

public class Test2 {
    public static void main(String[] args) {
        int k = 100;
        Integer int1 = k;
        Integer int2 = k;
        System.out.println("a." + (int1 == int2));
        k = 200;
        Integer int3 = k;
        Integer int4 = k;
        System.out.println("b." + (int3 == int4));
        char c = 'A';
        Character char1 = c;
        Character char2 = c;
        System.out.println("c." + (char1 == char2));
        c = '国';
        Character char3 = c;
        Character char4 = c;
        System.out.println("d." + (char3 == char4));
    }
}




结果

a.true
b.false
c.true
d.false


------解决方案--------------------
lz要看一下Integer的源码就知道了
Integer i=123; //等同于 Integer i=Integer.valueOf(100);
下面是Integer.valueOf(int i)的源码
Java code

public static Integer valueOf(int i) {
    final int offset = 128;
    if (i >= -128 && i <= 127) { // must cache 
        return IntegerCache.cache[i + offset];
    }
        return new Integer(i);
    }
 private static class IntegerCache {
    private IntegerCache(){}

    static final Integer cache[] = new Integer[-(-128) + 127 + 1];

    static {
        for(int i = 0; i < cache.length; i++)
        cache[i] = new Integer(i - 128);
    }
    }