File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Comparing Objects Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Comparing Objects" Watch "Comparing Objects" New topic

Comparing Objects

John Rainey

Joined: Dec 05, 2002
Posts: 17
Suppose I have a class:
public class User{
private String userId = null;
private Name name = null;
private List list = null;
// corresponding getter and setter methods
// left out because of space
Now suppose I have 2 User objects and I want to compare the 2 to see if they contain the same contents. What is the best and most efficient way to compare the objects. I know you can use reflection to get the properties and then get the values, but it becomes more complicated when their are lists or other objects involved besides Strings.
Rodney Woodruff
Ranch Hand

Joined: Dec 04, 2001
Posts: 80
One way is to override the equals method for your User object. This method is inherited from object and does a simple comparison to see if the references point to the same object in memory.
However, if you override the equals method, you should also look into overriding the hashcode method.
Search this forum for the topic of overriding equals and hashcode to get more ideas about how to implement this. This particular question is asked and answered quite often.
I would also search the Programmer Certification forum as it is discussed there as a matter of course because it is required to pass the exam.

Hope This Helps
Peter den Haan
Ranch Hand

Joined: Apr 20, 2000
Posts: 3252
I'm assuming that userId and name will not be null by the time you're calling equals() or hashCode(). I'm also assuming that whatever is stored in "list" will also implement equals() and hashCode().
- Peter
I agree. Here's the link:
subject: Comparing Objects
jQuery in Action, 3rd edition