-->
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.  [ 4 posts ] 
Author Message
 Post subject: HashSet and Contains, what am I doing wrong?
PostPosted: Thu Sep 30, 2004 3:31 pm 
Newbie

Joined: Thu Sep 30, 2004 3:19 pm
Posts: 3
Hi all!

I create an assignment to mCompany, and test that mCompany has that assignment. So this one passes:

assertTrue("Company should have the assigment", contain(assignment,
mCompany.getAssignments()));

But not this one:
assertTrue("Company should have the assigment", mCompany.getAssignments().contains(assignment));

contain(..., ...) is simple as:

private boolean contain(Assignment a, Set s) {
Iterator i = s.iterator();
while (i.hasNext()) {
Assignment b = (Assignment) i.next();
if (b.equals(a))
return true;
}
return false;
}

And Assignment has both equals(...) and hashCode(). Why HashSet.contains(...) returns false but I can find it when iterating through the set?!

Please help!

Elixir


Top
 Profile  
 
 Post subject:
PostPosted: Thu Sep 30, 2004 4:17 pm 
Beginner
Beginner

Joined: Tue Dec 09, 2003 3:27 pm
Posts: 21
does your hashCode value change after it's added to the collection? I suspect it does, in that case the contains method on the HashSet loses the reference to it and can't find it. See http://www.hibernate.org/109.html and http://forum.hibernate.org/viewtopic.php?t=928172 for more information.


Top
 Profile  
 
 Post subject:
PostPosted: Fri Oct 01, 2004 9:25 am 
Newbie

Joined: Thu Sep 30, 2004 3:19 pm
Posts: 3
Thanks, that solved my problem. It seems that HashSet does not use equals(...) to check if a object is in the set - even though Java 1.4.2 documents say:

contains:
Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that (o==null ? e==null : o.equals(e)).


Top
 Profile  
 
 Post subject:
PostPosted: Fri Oct 01, 2004 3:57 pm 
Hibernate Team
Hibernate Team

Joined: Tue Sep 09, 2003 2:10 pm
Posts: 3246
Location: Passau, Germany
Your objects have to obey the hashCode/equals contract of course.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 4 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.