0

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...

Neha Gupta
  • 847
  • 1
  • 8
  • 15
  • http://stackoverflow.com/a/27609/1083581 – happybuddha Jun 26 '13 at 12:40
  • 2
    This is a bit general. What is your real-world question? And yes, your assumption is correct (to a point). I mean, you can compare two objects without overriding equals, but they will not be equal for the reason you state. – Mark Chorley Jun 26 '13 at 12:40
  • you have mentioned answer in your own question. – Uniruddh Jan 24 '14 at 13:54
  • possible duplicate of [When do I need to override equals and hashcode methods?](http://stackoverflow.com/questions/13134050/when-do-i-need-to-override-equals-and-hashcode-methods) – Raedwald Jul 06 '14 at 12:03

4 Answers4

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.

herman
  • 11,740
  • 5
  • 47
  • 58
0

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.

AllTooSir
  • 48,828
  • 16
  • 130
  • 164
0

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.

Martin
  • 3,018
  • 1
  • 26
  • 45
0

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
}
Marco Forberg
  • 2,634
  • 5
  • 22
  • 33