• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing Objects

 
John Rainey
Greenhorn
Posts: 17
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
Thanks
 
Rodney Woodruff
Ranch Hand
Posts: 80
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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: http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic