转自:
http://jessdy.javaeye.com/blog/174011首先:
- public static void main(String []args) {
- Integer a = 100;
- Integer b = 100;
- System.out.println(a==b);
- }
public static void main(String []args) { Integer a = 100; Integer b = 100; System.out.println(a==b); //true } - public static void main(String []args) {
- Integer a = 200;
- Integer b = 200;
- System.out.println(a==b);
- }
public static void main(String []args) { Integer a = 200; Integer b = 200; System.out.println(a==b); //false } 原因:
1。
java在编译的时候 Integer a = 100; 被翻译成-> Integer a = Integer.valueOf(100);
2。比较的时候仍然是对象的比较
3。在jdk源码中
- public static Integer valueOf(int i) {
- final int offset = 128;
- if (i >= -128 && i <= 127) {
- return IntegerCache.cache[i + offset];
- }
- return new Integer(i);
- }
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 = new Integer(i - 128);
- }
- }
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 = new Integer(i - 128); } } 这边是
java为了提高效率,初始化了-128--127之间的整数对象
所以在赋值在这个范围内都是同一个对象。
再加一句
Integer a = 100;
a++;
//这边a++是新创建了一个对象,不是以前的对象。
- public static void main(String []args) {
- Integer a = 100;
- Integer b = a;
- a++;
- System.out.println(a==b);
- }
public static void main(String []args) { Integer a = 100; Integer b = a; a++; System.out.println(a==b); } 打印就是false
对于127--128没有多大关系,但是在这范围之外就影响性能了吧