Java:等于和== [英] Java: equals and ==

查看:68
本文介绍了Java:等于和==的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们看一下我们有2个对用户定义类实例的引用,在Java中是a和b.会不会有这样的情况a == b但a.equals(b)返回false?

Lets see we have 2 references to instances of a user-defined class, a and b in Java. Can there ever be a situation where a == b but a.equals(b) return false?

推荐答案

当然! .equals()的实现完全取决于该类,因此我可以这样写:

Sure! The implementation of .equals() is completely up to the class, so I could write:

class Foo
    public boolean equals(Object other) {
        return false;
    }
}

现在,您通过两个实例都没关系-即使两次完全相同的实例-我总是要说它们不相等.

Now it doesn't matter what two instances you pass — even the exact same instance twice — I'm always going to say they're not equal.

这种特别的设置很愚蠢,但是它说明您可以从同一对象的 .equals()两次获得 false 结果.

This particularly setup is silly, but it illustrates that you can get a false result from .equals() for the same object twice.

请注意,我们在这里谈论的是 会发生什么,而不是 应该 发生什么.任何类都不应实现声称对象不等于自身的 .equals 方法.对于受信任的代码,可以合理地假设这种情况永远不会发生.

Note that we're talking here about what can happen, not what should. No class should ever implement a .equals method that claims an object isn't equal to itself. For trusted code, it's reasonable to assume this will never happen.

这篇关于Java:等于和==的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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