why 2 objects of Integer class in Java cannot be e

2019-06-20 20:44发布

my code is:

public class Box
{
  public static void main(String[] args)
  {
     Integer z = new Integer(43);
     z++;

     Integer h = new Integer(44);

     System.out.println("z == h -> " + (h == z ));
  }
}

Output:-

z == h -> false

why the output is false when the values of both the objects is equal?

Is there any other way in which we can make the objects equal?

7条回答
【Aperson】
2楼-- · 2019-06-20 20:48

You are trying to compare two different object and not their values. z and h points to two different Integer object which hold same value.

z == h 

Will check if two objects are equal. So it will return false.

If you want to compare values stored by Integer object use equals method.


Integer z = new Integer(43);   // Object1  is created with value as 43.
z++;                           // Now object1 holds 44.

Integer h = new Integer(44); // Object2 is created with value as 44.

So at the end we have two different Integer object ie object1 and object2 with value as 44. Now

z = h

This will check if objects pointed by z and h is same. ie object1 == object2 which is false. If you do

Integer z = new Integer(43);   // Object1  is created with value as 43.
z++;                           // Now object1 holds 44. Z pointing to Object1

Integer h = z;                 // Now h is pointing to same object as z.

Now

z == h  

will return true.

This might help http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

查看更多
劫难
3楼-- · 2019-06-20 20:52

No. Use h.equals(z) instead of h == z to get the equality behavior you expect.

查看更多
劳资没心,怎么记你
4楼-- · 2019-06-20 20:53

Integer is an object, not a primitive. If z & h were primitives, == would work just fine. When dealing with objects, the == operator doesn't check for equality; it checks if the two references point to the same object.

As such, use z.equals(h); or h.equals(z); These should return true.

查看更多
祖国的老花朵
5楼-- · 2019-06-20 21:00

Integer is Object not primitive (int) And Object equality compare with equals method.

When you do z == h it will not unbox into int value unless it checks both Integer reference(z & h) are referring same reference or not.

As it is derived in documentation -

The result is true if and only if the argument is not null and is an Integer object that contains the same int value as this object.

System.out.println("z == h -> " + h.equals( z));

It will print true.

查看更多
我欲成王,谁敢阻挡
6楼-- · 2019-06-20 21:02

check to make sure you can use z++ on the Integer object.

查看更多
Bombasti
7楼-- · 2019-06-20 21:05

Read this: http://docs.oracle.com/javase/1.5.0/docs/api/java/lang/Integer.html

Integer is Object you compare address/references/pointers of objects not values.

Integer a = Integer(1);
Integer b = Integer(1);

a == b; // false
a.compareTo(b); // true
查看更多
登录 后发表回答