aspose file tools*
The moose likes Beginning Java and the fly likes puzzling set behavior Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "puzzling set behavior" Watch "puzzling set behavior" New topic
Author

puzzling set behavior

Ken Jones
Greenhorn

Joined: Oct 17, 2009
Posts: 2
Here is a snippet of the relevant parts of some JUnit code that is puzzling me:

This test passes, but I expect it to fail. I expect the size of the set to be 1 instead of two because I am adding two different objects that are equal to one another. I didn't think the second call to add() would add another member to the set because of this equality. What am I missing?

Thanks,

Ken
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

Ken Jones wrote:This test passes, but I expect it to fail. I expect the size of the set to be 1 instead of two because I am adding two different objects that are equal to one another. I didn't think the second call to add() would add another member to the set because of this equality. What am I missing?


HashSet depends on the equals() and hashCode() method to determine equality -- so you need to show us the code for those two methods.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Ken Jones
Greenhorn

Joined: Oct 17, 2009
Posts: 2
While I was copying my code into this reply I found the source of my problem, in an equals() method, of course. Thanks for your help!

Ken
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: puzzling set behavior