# 想想 Integer 128 这个东东

2017/03/14 10:51

### 简单粗暴，用代码说话

public class TestSubstring {

public static void main(String[] args) {

/**compare Integer when Integer >=-128 and Integer<=127***/
Integer s1 = 127;
Integer s2 = 127;
System.out.println("s1 == s2:"+(s1==s2));
System.out.println("s1.equals(s2):"+(s1.equals(s2)));
System.out.println("\r");
/**compare Integer when Integer <-128 and Integer>127***/
Integer s3 = 128;
Integer s4 = 128;
System.out.println("s3 == s4:"+(s3==s4));
System.out.println("s3.equals(s4):"+(s3.equals(s4)));
}
}


### 进入 JDK 查看源码

    /**
* Returns a <tt>Integer</tt> instance representing the specified
* <tt>int</tt> value.
* If a new <tt>Integer</tt> instance is not required, this method
* should generally be used in preference to the constructor
* {@link #Integer(int)}, as this method is likely to yield
* significantly better space and time performance by caching
* frequently requested values.
*
* @param  i an <code>int</code> value.
* @return a <tt>Integer</tt> instance representing <tt>i</tt>.
* @since  1.5
*/
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);
}
}


0 评论
1 收藏
0