Integer i=3 vs Integer i= new Integer (3) [duplica

2020-02-05 04:09发布

I am comparing 2 pieces of code. First

Integer i=3;
Integer j=3;
if(i==j)
   System.out.println("i==j");  //prints i==j              

Second,

Integer i=3;
Integer j=new Integer(3);
if(i==j)
   System.out.println("i==j"); // does not print

I have doubt that in the first snippet why i==j is being printed? Shouldn't the references be different?

标签: java
9条回答
smile是对你的礼貌
2楼-- · 2020-02-05 05:03

Because in the second peice of code your first integer is being auto-boxed while the second is not.

This means a new Integer instance is being created on the fly. These 2 object instances are different. The equality check will return false there as the two instances are actually different pieces of memory.

查看更多
乱世女痞
3楼-- · 2020-02-05 05:04

In a similar fashion to strings, when autoboxing is used, such as in

Integer i = 3;
Integer j = 3;

Java can draw from a pool of prefabricated objects. In the case of j, there's already an Integer instance representing the value of 3 in the pool, so it draws from that. Thus, i and j point to the same thing, thus i == j.

In your second example, you're explicitly instantiating a new Integer object for j, so i and j point to different objects, thus i != j.

查看更多
做自己的国王
4楼-- · 2020-02-05 05:06

I have doubt that in the first snippet why i==j is being printed? Shouldn't the references be different?

Because,

    Integer i=3;
    Integer j=3;

are internally using Integer#valueOf() to perform autoBoxing . And oracle doc says about valueOf() method that:

Returns an Integer instance representing the specified int value. If a new Integer instance is not required, this method should generally be used in preference to the constructor Integer(int), as this method is likely to yield significantly better space and time performance by caching frequently requested values. This method will always cache values in the range -128 to 127, inclusive, and may cache other values outside of this range.

Since the value 3 is cached therefore, both variables i and j are referencing the same object. So, i==j is returning true. Integer#valueOf() uses flyweight pattern.

查看更多
登录 后发表回答