using equals method in same class without overriding

杀马特。学长 韩版系。学妹 提交于 2019-12-13 06:02:09

问题


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

Can we compare a1 & a2 using equals method and without overriding it.. ? Also the value should be compared not the address at a1 & a2...


回答1:


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.




回答2:


It depends on your requirement. You can implement a Comparator and override its compare() as per your need. The logic inside the compare() need not use equals() or hashCode() at all. I believe checking for equality and comparing objects are different thing.




回答3:


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.

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.




回答4:


You could try to do this with a Comparator: (the compare method should return 0 if .equals() would return true)

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
}


来源:https://stackoverflow.com/questions/17320172/using-equals-method-in-same-class-without-overriding

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!