aspose file tools*
The moose likes Beginning Java and the fly likes object comparison Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "object comparison" Watch "object comparison" New topic
Author

object comparison

Shruthi Babu
Ranch Hand

Joined: May 04, 2007
Posts: 54
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

Joined: Aug 05, 2005
Posts: 3446
    
  12
See this post


Joanne
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38340
    
  23
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

Joined: Oct 27, 2005
Posts: 19670
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Shruthi Babu
Ranch Hand

Joined: May 04, 2007
Posts: 54
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

Joined: Oct 04, 2007
Posts: 101
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.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: object comparison