2

Is there a way in which we can equate two objects?

I know that we can use equals, but the problem is that I need to write a utility which can compare any two objects implementing same interface.

Now the object can have 1 attribute, or 2 attribute or can have 100 attribute. and i need to compare each and every attribute to prove then exactly equal.

3
  • You can try and use reflection to iterate the two objects attributes and compare them. (it is implied in your question that you don't to implement equals or a comparator...) Commented Feb 29, 2012 at 12:00
  • @Ido. CO : can you please give an example how to do the same. I Know how to use reflection, but not sure exactly how to do that. Commented Feb 29, 2012 at 12:08
  • I'll look for a good example for you. Commented Feb 29, 2012 at 12:23

3 Answers 3

2

You may have a look at the Apache Commons helper classes EqualsBuilder and HashCodeBuilder. These classes provides methods to build good equals and hashCode method for any class.

Sign up to request clarification or add additional context in comments.

Comments

0

This can be done using reflection. If you don't want to write your own utility, you can use something like Unitils, which provides a class called ReflectionAssert.

See also Is there a Java reflection utility to do a deep comparison of two objects?

Comments

0

If you don't want to implement equals or a comparator, you can try and do it by reflection.

Iterate over the two objects fields and compare them -

Field[] fields1 = o1.getClass().getDeclaredFields(); Field[] fields2 = o2.getClass().getDeclaredFields(); for (int i = 0; i++ ; i>fields.lenght) { // compare the two fields under the assumption that if the two // objects are the same their fields will be the same in each iteration } 

use field.get(Object) to retrieve the value of the field

Since there might be nesting and collections of object involved, you'll have to do it recursively for each element, and pointer cycles might present a problem. so if you're expecting cycles you'll have to implement more complex solution (you'll have to store the actual pointers. and check that you are not trying to recursively compare the same elements twice).

2 Comments

It's not that easy. How do you handle nested collections? How do you make sure you're not ending in a cycle? Implementing this is not trivial...
About comparing collections- this comparison should be done recursively for every element (or use it's implementation of equals instead). About cycles - This is a problem. you shouldn't you use this method if you expect cycles (although there is a solution: addresses memoization, but it's ugly)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.