- How to compare two java objects [duplicate]
- 5 Answers 5
- Class Objects
- Method Summary
- Methods declared in class java.lang.Object
- Method Details
- equals
- deepEquals
- hashCode
- hash
- toString
- toString
- toIdentityString
- compare
- requireNonNull
- requireNonNull
- isNull
- nonNull
- requireNonNullElse
- requireNonNullElseGet
- requireNonNull
- checkIndex
- Compare objects java equals
- Method Summary
- Methods inherited from class java.lang.Object
- Method Detail
- equals
- deepEquals
- hashCode
- hash
- toString
- toString
- compare
- requireNonNull
- requireNonNull
How to compare two java objects [duplicate]
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?
5 Answers 5
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()
See this question for more details on implementing a hash function.
@Aubin Usually, prime numbers are used in hash code generation. If I’m not mistaken, it reduces the chances that there will be collisions on the generated hashes. As to why use 37, I guess it is just a popular choice, I don’t know of any particular reason for using 37 instead of, say, 13.
@John Your equals could also check for other == this , although this is not necessary, it would return true without verifying each field.
@Aubin I think 37 is from Monte Carlo tests, and the same tests on String shows that 31 is also acceptable and its less complicated, so 31 is used for java String hashCode. This is shown in Figure 5.45 in Data structures and Algorithm analysis. A clear figure could be found at faculty.cs.uwlax.edu/~mallen/courses/cs340/lec16.pdf
You need to Override equals and hashCode .
equals will compare the objects for equality according to the properties you need and hashCode is mandatory in order for your objects to be used correctly in Collections and Maps
You need to implement the equals() method in your MyClass .
The reason that == didn’t work is this is checking that they refer to the same instance. Since you did new for each, each one is a different instance.
The reason that equals() didn’t work is because you didn’t implement it yourself yet. I believe it’s default behavior is the same thing as == .
Note that you should also implement hashcode() if you’re going to implement equals() because a lot of java.util Collections expect that.
You have to correctly override method equals() from class Object
Edit: I think that my first response was misunderstood probably because I was not too precise. So I decided to to add more explanations.
Why do you have to override equals()? Well, because this is in the domain of a developer to decide what does it mean for two objects to be equal. Reference equality is not enough for most of the cases.
For example, imagine that you have a HashMap whose keys are of type Person. Each person has name and address. Now, you want to find detailed bean using the key. The problem is, that you usually are not able to create an instance with the same reference as the one in the map. What you do is to create another instance of class Person. Clearly, operator == will not work here and you have to use equals().
But now, we come to another problem. Let’s imagine that your collection is very large and you want to execute a search. The naive implementation would compare your key object with every instance in a map using equals(). That, however, would be very expansive. And here comes the hashCode(). As others pointed out, hashcode is a single number that does not have to be unique. The important requirement is that whenever equals() gives true for two objects, hashCode() must return the same value for both of them. The inverse implication does not hold, which is a good thing, because hashcode separates our keys into kind of buckets. We have a small number of instances of class Person in a single bucket. When we execute a search, the algorithm can jump right away to a correct bucket and only now execute equals for each instance. The implementation for hashCode() therefore must distribute objects as evenly as possible across buckets.
There is one more point. Some collections require a proper implementation of a hashCode() method in classes that are used as keys not only for performance reasons. The examples are: HashSet and LinkedHashSet. If they don’t override hashCode(), the default Object hashCode() method will allow multiple objects that you might consider «meaningfully equal» to be added to your «no duplicates allowed» set.
Some of the collections that use hashCode()
Have a look at those two classes from apache commons that will allow you to implement equals() and hashCode() easily
Class Objects
This class consists of static utility methods for operating on objects, or checking certain conditions before operation. These utilities include null -safe or null -tolerant methods for computing the hash code of an object, returning a string for an object, comparing two objects, and checking if indexes or sub-range values are out of bounds.
Method Summary
Checks if the sub-range from fromIndex (inclusive) to fromIndex + size (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).
Checks if the sub-range from fromIndex (inclusive) to fromIndex + size (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).
Checks if the sub-range from fromIndex (inclusive) to toIndex (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).
Checks if the sub-range from fromIndex (inclusive) to toIndex (exclusive) is within the bounds of range from 0 (inclusive) to length (exclusive).
Checks that the specified object reference is not null and throws a customized NullPointerException if it is.
Checks that the specified object reference is not null and throws a customized NullPointerException if it is.
Returns the first argument if it is non- null and otherwise returns the non- null value of supplier.get() .
Returns a string equivalent to the string returned by Object.toString if that method and hashCode are not overridden.
Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.
Methods declared in class java.lang.Object
Method Details
equals
Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null , true is returned. Otherwise, if the first argument is not null , equality is determined by calling the equals method of the first argument with the second argument of this method. Otherwise, false is returned.
deepEquals
Returns true if the arguments are deeply equal to each other and false otherwise. Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by using the equals method of the first argument.
hashCode
hash
Generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]) . This method is useful for implementing Object.hashCode() on objects containing multiple fields. For example, if an object that has three fields, x , y , and z , one could write:
@Override public int hashCode()
Warning: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object) .
toString
toString
Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.
toIdentityString
Returns a string equivalent to the string returned by Object.toString if that method and hashCode are not overridden.
compare
Returns 0 if the arguments are identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned. Note that if one of the arguments is null , a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values.
requireNonNull
Checks that the specified object reference is not null . This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated below:
requireNonNull
Checks that the specified object reference is not null and throws a customized NullPointerException if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below:
public Foo(Bar bar, Baz baz)
isNull
nonNull
requireNonNullElse
requireNonNullElseGet
Returns the first argument if it is non- null and otherwise returns the non- null value of supplier.get() .
requireNonNull
Checks that the specified object reference is not null and throws a customized NullPointerException if it is. Unlike the method requireNonNull(Object, String) , this method allows creation of the message to be deferred until after the null check is made. While this may confer a performance advantage in the non-null case, when deciding to call this method care should be taken that the costs of creating the message supplier are less than the cost of just creating the string message directly.
checkIndex
Compare objects java equals
This class consists of static utility methods for operating on objects. These utilities include null -safe or null -tolerant methods for computing the hash code of an object, returning a string for an object, and comparing two objects.
Method Summary
Checks that the specified object reference is not null and throws a customized NullPointerException if it is.
Checks that the specified object reference is not null and throws a customized NullPointerException if it is.
Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.
Methods inherited from class java.lang.Object
Method Detail
equals
Returns true if the arguments are equal to each other and false otherwise. Consequently, if both arguments are null , true is returned and if exactly one argument is null , false is returned. Otherwise, equality is determined by using the equals method of the first argument.
deepEquals
Returns true if the arguments are deeply equal to each other and false otherwise. Two null values are deeply equal. If both arguments are arrays, the algorithm in Arrays.deepEquals is used to determine equality. Otherwise, equality is determined by using the equals method of the first argument.
hashCode
hash
Generates a hash code for a sequence of input values. The hash code is generated as if all the input values were placed into an array, and that array were hashed by calling Arrays.hashCode(Object[]) . This method is useful for implementing Object.hashCode() on objects containing multiple fields. For example, if an object that has three fields, x , y , and z , one could write:
@Override public int hashCode()
Warning: When a single object reference is supplied, the returned value does not equal the hash code of that object reference. This value can be computed by calling hashCode(Object) .
toString
toString
public static String toString(Object o, String nullDefault)
Returns the result of calling toString on the first argument if the first argument is not null and returns the second argument otherwise.
compare
Returns 0 if the arguments are identical and c.compare(a, b) otherwise. Consequently, if both arguments are null 0 is returned. Note that if one of the arguments is null , a NullPointerException may or may not be thrown depending on what ordering policy, if any, the Comparator chooses to have for null values.
requireNonNull
public static T requireNonNull(T obj)
Checks that the specified object reference is not null . This method is designed primarily for doing parameter validation in methods and constructors, as demonstrated below:
requireNonNull
Checks that the specified object reference is not null and throws a customized NullPointerException if it is. This method is designed primarily for doing parameter validation in methods and constructors with multiple parameters, as demonstrated below: