Forums Register Login

How to equal same class objects

+Pie Number of slices to send: Send
if i write a class i,e ClassA then i create two objects for that respective class, so here how can i equal those two objects.
+Pie Number of slices to send: Send
U can use equals method. equals method is inhereted from java.lang.Object. It will look like this:

ClassA classA1 = new ClassA(); //provide the constructor arguments
ClassA classA2 = new ClassA(); //provide the constructor arguments

if (classA1.equals(classA2)) {
System.out.println("Equals");
}
else {
System.out.println("Don't equals");
}

Of course you have to override this method to provide a kind of comparison to determine whether those 2 objects are equals.


I hope your problem are solved.



cheers


Jeffry Kristianto Yanuar
+Pie Number of slices to send: Send
By overriding the "public boolean equals(Object)" method.

How you do this is all up to you, but you should a) read the API of Object for some rules, and b) also override hashCode().

Now some checks you always want to perform:
- if the passed object is the same object, return true - this is for speed mostly
- if the passed object is null, return false
- if the passed object is of an incompatible class, return false

In code:

Instead of "getClass() != o.getClass()" you also often see code like "!getClass().isInstance(o)", or the more hardcoded version "!(o instanceof MyClass)".

While the latter two are perfect for final classes, they may lead to violation of one of the API rules for equals, if a subclass defines its own equals method using the same principle. If that's the case, then equals is no longer symmetric, since an instance of the subclass can be equal to an instance of your own class, but vice versa they will be unequal.
I like you because you always keep good, crunchy cereal in your pantry. This tiny ad agrees:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 671 times.
Similar Threads
x.hasCode() == y.hashCode()
How to check the two objects are same?
Inquisition qustion regarding equals() and hashCode()
Test for equality of two objects
regarding scjp 1.5
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 03:03:04.