I've got a Java class, here's an example:
public class Car { private int fuelType; private Date made; private String name; . . . // and so on
Now let's say I have two car objects and I want to compare if all their variables are equal.
Right now, I've solved this by overriding method equals(Object o)
and I check if all the variables match in both objects.
The problem here is that if I have 20 classes, I'll have to override equals(Object o)
in every single one of them.
Is there a way create some sort of universal method that could compare any of the two objects that I pass to it and let me know if they match in every single variable or not?
The equals () method of the Object class compare the equality of two objects. The two objects will be equal if they share the same memory address. The method parses a reference object as a parameter. It returns true if the objects are equal, else returns false.
Since every object in Java inherits from the Object class, this method can be overridden as needed. To test reference equality, you can use == (equals equals) to determine if the object references are referencing the same memory location.
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). Objects are identical when they share the class identity. For example, the expression obj1==obj2 tests the identity, not equality.
Let’s use above mentioned methods to check if two objects are equal in JavaScript. The JSON.stringify () is a built-in JavaScript method that can convert an object into a string, and then comparing strings is more accessible than reaching the whole object. It takes an object name as the parameter.
You have a few options for automating Equals & Hashcode (option #3 BLEW MY MIND!):
EqualsAndHashCode
annotation on ya class and be done with it. I recommend using Project Lombok. It adds a touch of magic into the build (but not much) and so requires a plugin for your IDE to behave nicely but they are a small price to pay for no boilerplate code. Lombok is an annotation processor that run at compile time so you have no runtime performance hit. you can use :
org.apache.commons.lang.builder.CompareToBuilder.reflectionCompare(Object lhs, Object rhs);
it uses reflection to compare the fileds here is the javadoc : javadoc
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