Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two java objects [duplicate]

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?

like image 291
Roy Hinkley Avatar asked Apr 17 '13 19:04

Roy Hinkley


People also ask

Can you use == to compare objects in Java?

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

Can you use == to compare objects?

The == operator compares whether two object references point to the same object. For example: System. out.

How do you compare two sets of objects in Java?

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.

Can you compare two objects of the same class?

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.


1 Answers

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.

like image 86
John Kugelman Avatar answered Sep 26 '22 01:09

John Kugelman