I have two java objects that are instantiated from the same class.
MyClass myClass1 = new MyClass(); MyClass myClass2 = new MyClass();
If I set both of their properties to the exact same values and then verify that they are the same
if(myClass1 == myClass2){ // objects match ... } if(myClass1.equals(myClass2)){ // objects match ... }
However, neither of these approaches return a true value. I have checked the properties of each and they match.
How do I compare these two objects to verify that they are identical?
In Java, the == operator compares that two references are identical or not. Whereas the equals() method compares two objects. Objects are equal when they have the same state (usually comparing variables).
The == operator compares whether two object references point to the same object. For example: System. out.
The equals() method of java. util. Set class is used to verify the equality of an Object with a Set and compare them. The method returns true if the size of both the sets are equal and both contain the same elements.
This can occur through simple assignment, as shown in the following example. Value equality means that two objects contain the same value or values. For primitive value types such as int or bool, tests for value equality are straightforward.
You need to provide your own implementation of equals()
in MyClass
.
@Override public boolean equals(Object other) { if (!(other instanceof MyClass)) { return false; } MyClass that = (MyClass) other; // Custom equality check here. return this.field1.equals(that.field1) && this.field2.equals(that.field2); }
You should also override hashCode()
if there's any chance of your objects being used in a hash table. A reasonable implementation would be to combine the hash codes of the object's fields with something like:
@Override public int hashCode() { int hashCode = 1; hashCode = hashCode * 37 + this.field1.hashCode(); hashCode = hashCode * 37 + this.field2.hashCode(); return hashCode; }
See this question for more details on implementing a hash function.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With