Integer ,==,int 的使用

转载自:
https://www.cnblogs.com/sunjiguang/p/5685002.html

面试比较常见的题目:自己也经常忘记,所以就记下来了

上代码:

1 Integer a = 1000,b=1000;  
2 Integer c = 100,d=100;  
3   
4 System.out.println(a==b);  
5 System.out.println(c==d);

输出的正确结果分别是  falsetrue

原因:看Integer.java类

复制代码
public static Integer valueOf(int i) {  
      return  i >= 128 || i < -128 ? new Integer(i) : SMALL_VALUES[i + 128];  
  }  
  
  /** 
   * A cache of instances used by {@link Integer#valueOf(int)} and auto-boxing 
   */  
  private static final Integer[] SMALL_VALUES = new Integer[256];  
  
  static {  
      for (int i = -128; i < 128; i++) {  
          SMALL_VALUES[i + 128] = new Integer(i);  
      }  
  }
复制代码

当声明Integer a=100 的时候,会进行自动装箱操作,即调用 valueOf() 把基本数据类型转换成Integer对象,valueOf()方法中可以看出,

程序把 -128—127之间的数缓存下来了(比较小的数据使用频率较高,为了优化性能),所以当Integer的对象值在-128—127之间的时候是

使用的缓存里的同一个对象,所以结果是true,而大于这个范围的就会重新new对象。

2. Integer 和 int

上代码:

复制代码
Integer a = new Integer(1000);  
int b = 1000;  
Integer c = new Integer(10);  
Integer d = new Integer(10);  
System.out.println(a == b);  
System.out.println(c == d); 
复制代码

正确答案:true ,false

解析:

第一个:值是1000,肯定和缓存无关,但是b的类型是int,当int和Integer进行 == 比较的时候 ,java会将Integer进行自动拆箱操作,

再把Integer转换成int,所以比较的是int类型的数据,   so 是true

第二个:虽然值是10 在缓存的范围内,但是 c,d都是我们手动new出来的,不需要用缓存, so 是false

 

---------------------------------------------------------------------阿纪----------------------------------------------------------------------

猜你喜欢

转载自blog.csdn.net/ajiu_9999/article/details/86572898