equals()和运算符“ ==”在java中 [英] equals() and operator "==" in java

查看:76
本文介绍了equals()和运算符“ ==”在java中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道 equals()将比较对象的值,'=='运算符将检查变量是否指向相同的内存。

I know that equals() will compare the value of objects, the '==' operator will check if the variable point to the same memory.

我不明白 equals()如何比较对象的值,例如:

I do not understand how equals() compare the value of objects, for example:

class Test {
    public Test(int x, float y) {
        this.x = x;
        this.y = y;
    }

    int x,
    float y;
}

Test test1 = new Test(1,2.0);
Test test2 = new Test(1,2.0);

因此,如果我使用 equals()

那如果我们在谈论字符串呢?

And what about if we are talking about String? using equals() and operator "==", do we still need to override the equals()?

推荐答案

否,如果使用equals()和运算符 ==,我们是否仍需要覆盖equals()?您不会覆盖类中的 equals 方法,那么 equals == 。请参见文档

No, if you don't override the equals-method in your class, then equals is the same as ==. See the documentation for this:


类Object
的equals方法实现了最有区别的

对象的等价关系;也就是说,对于任何非空
参考值x和y,当且仅当x和y
引用同一个对象(x == y具有$ b)时,此方法
返回true $ b的值为true)。

The equals method for class Object implements the most discriminating possible equivalence relation on objects; that is, for any non-null reference values x and y, this method returns true if and only if x and y refer to the same object (x == y has the value true).

文档还说明了等于方法,以防万一。

The documentation also states what requirements there are for equals methods in case you want to implement it.

这篇关于equals()和运算符“ ==”在java中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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