Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

puzzling set behavior

 
Ken Jones
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Marshal
Pie
Posts: 21413
84
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Ken Jones
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic