问题描述
是否可以在不重写equals方法的情况下比较两个相同类的对象?如果是,请让我知道如何.根据我的说法,不可能在不进行覆盖的情况下比较两个相同类的对象的变量,因为对象包含内存地址而不是变量值.
Is it possible to compare 2 objects of same class without overriding equals method.. ?If yes, please let me know how.. ?According to me, it is not possible to compare variables of 2 different objects of same class without overriding because object contains memory address and not the variable value.
class A {
int x;
A(int x) {
this.x=x; }
}
A a1=new A(5);
A a2=new A(4);
我们可以比较a1和...吗?a2使用equals方法而不覆盖它.而且,应该比较该值而不是a1和amp; 2处的地址.a2 ...
Can we compare a1 & a2 using equals method and without overriding it.. ? Also the value should be compared not the address at a1 & a2...
推荐答案
基本对象身份可以使用 ==
运算符或 equals()
进行验证.不被覆盖.如果要定义自己的自定义 equals()
行为,则当然需要覆盖它.
Basic object identity can be verified using the ==
operator, or equals()
if it is not overridden. If you want to define your own custom equals()
behaviour, of course you will need to override it.
这篇关于在同一个类中使用equals方法而不覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!