-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 
Author Message
 Post subject: How to write hashCode and compareTo methods
PostPosted: Fri Oct 13, 2006 2:46 pm 
Newbie

Joined: Wed Dec 15, 2004 1:58 pm
Posts: 16
Location: Prague, Czech Republic
I need to mix saved and unsaved objects in Set.

I have the following equals method:

Code:
   
public boolean equals(Object obj) {
      if (!(obj instanceof MyClass))
         return false;
      else {
         if (obj==this) return true;
         MyClass myEntity= (MyClass) obj;
         if (null == this.getId() || null == myEntity.getId())
            return false;
         else
            return (this.getId().equals(myEntity.getId()));
      }
   }


Eg. objects with tha same ID are equal (whether or not loaded in the same session).

How to write compareTo and hasCode methods to be compatible with HashSet and TreeSet?
The problem is that hashCode (compareTo) method result have to change after my object is saved (eg. id!=null).

Or should I not mix saved and unsaved objects in TreeSet (HashSet)?

I have ID's assigned by database.

Thanks helping me.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Oct 13, 2006 5:36 pm 
Newbie

Joined: Thu Aug 10, 2006 12:25 am
Posts: 13
When I ran into this problem, I save/persisted the child first and then added it to the Set, could not find another way around it. I was going to investigate a refresh of the parent but it seemed rather expensive to do.

The above worked for me


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 2 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.