简体   繁体   English

在同一个类中使用equals方法而不覆盖

[英]using equals method in same class without overriding

Is it possible to compare 2 objects of same class without overriding equals method.. ? 是否可以在不重写equals方法的情况下比较相同类的2个对象? 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);

Can we compare a1 & a2 using equals method and without overriding it.. ? 我们可以使用equals方法比较a1和a2而不覆盖它吗? Also the value should be compared not the address at a1 & a2... 同样应该比较该值而不是a1和a2处的地址...

Basic object identity can be verified using the == operator, or equals() if it is not overridden. 基本对象标识可以使用==运算符进行验证,如果不被覆盖,则可以使用equals()进行验证。 If you want to define your own custom equals() behaviour, of course you will need to override it. 如果要定义自己的自定义equals()行为,则当然需要重写它。

It depends on your requirement. 这取决于您的要求。 You can implement a Comparator and override its compare() as per your need. 您可以根据需要实现一个Comparator并覆盖其compare() The logic inside the compare() need not use equals() or hashCode() at all. compare()内部的逻辑根本不需要使用equals()hashCode() I believe checking for equality and comparing objects are different thing. 我相信检查相等性和比较对象是不同的事情。

It depends on what you need to do. 这取决于您需要做什么。 Why don't override equals? 为什么不覆盖等于? It's the right way to go... 这是正确的方法...

You can still manually compare fields between objects, but it's cleaner to pack that into the equals method. 您仍然可以手动比较对象之间的字段,但是将其打包到equals方法中比较干净。

Now, if you're asking why not just use a == b, then it will not work in most cases because, as you state it, it is the Object reference that you're calling and not it's content. 现在,如果您要问为什么不只使用a == b,那么它在大多数情况下将不起作用,因为正如您声明的那样,它是您正在调用的对象引用,而不是其内容。

You could try to do this with a Comparator : (the compare method should return 0 if .equals() would return true ) 您可以尝试使用Comparator进行此操作:(如果.equals()返回true则compare方法返回0

public class YourClassComparator implements Comparator<YourClass> {
    @Override
    public int compare(YourClass left, YourClass right) {
        // do the comparison and return
        // <0 if left < right
        // 0 if left equals right
        // >0 if left > right
    }
}

and then use it to check for equality 然后用它来检查是否相等

if(new YourClassComparator().compare(yourClass1, yourClass2) == 0) {
    // objects are equal
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM