为什么在Java中的Integer类的2个对象不能相等 [英] why 2 objects of Integer class in Java cannot be equal

查看:158
本文介绍了为什么在Java中的Integer类的2个对象不能相等的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码是:

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 ));
  }
}

输出: -

z == h -> false

为什么两个对象的值相等时输出为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?

推荐答案

试图比较两个不同的对象,而不是它们的值。 z和h指向具有相同值的两个不同的整数对象。

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 

将检查两个对象是否相等。所以它会返回false。

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

如果要比较Integer对象存储的值,请使用 equals 方法。

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.

所以最后我们有两个不同的Integer对象object1和object2的值为44.
现在

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

z = h

这将检查z和h指向的对象是否相同。即 object1 == object2
这是false。
如果你这样做

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.

现在

z == h  

将返回true。

这可能有助于 http://www.programmerinterview.com/index.php/java-questions/java-whats-the-difference-between-equals-and/

这篇关于为什么在Java中的Integer类的2个对象不能相等的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆