• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

object comparison

 
Shruthi Babu
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I need to compare two objects if they are of same type and if there contents are equal . how can this be done in java

Any help is highly appreciated.

Thanks
Rohini
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
See this post
 
Campbell Ritchie
Sheriff
Posts: 48652
56
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Agree. The post by Rob Prime tells you what you need to know. Remember that instanceof and similar only work for final classes; otherwise use the bit about this.getClass() and other.getClass(). Make sure to put the null test in first; if the other object is null then you assume it is different.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Campbell Ritchie:
Remember that instanceof and similar only work for final classes; otherwise use the bit about this.getClass() and other.getClass().

If the itself method is final, you can use instanceof as well, as long as you hardcode the class. After all, if you compare two an object of class A with an object of a subclass of A and vice versa, both will check if the other is an instance of A. Both checks will return true, so symmetry has been achieved.
 
Shruthi Babu
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ok this works fine for normal scenarios. How to compare two object arrays which in turn might contains other object arrays ..

FOR EXAMPLE

I neeed to compare if two order[] objects are equal. the order object might contain other customer object , product objects etc..

product objects might inturn contain iterm objects...

is ther a easy way to achieve this in 1.4.2,

Any help is highly appreciated
 
Adam Schaible
Ranch Hand
Posts: 101
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no "1 liner" that will do it for you, but it's not _that_ difficult

What you might consider doing is looking at the 1.5 source for the Arrays and implementing something similar to the Arrays.equals(Object[] a, Object[] a2) method.



Remember, Java is open source - and if it doesn't take advantage of Generics, there's no reason you can't code up your own method. You might even copy the entire Array's class into your project.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic