This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
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
Similar Threads
Javascript - Arraylist
servlets and xml
Sort by Name
Sorting by 3 variables dynamically in arrayList