• Post Reply Bookmark Topic Watch Topic
  • New Topic

Adding class objects to a HashSet  RSS feed

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Having trouble adding Class (Dollar) objects to a HashSet (money), i have done this before with arraylists and i understand that HashSets are different in that they cannot contain duplicates. Currently when this code is compiled i am getting "null" printed when I run the "howFullDatWallet" method. Any advice would be greatly appreciated!

 
Sheriff
Posts: 22846
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're adding Dollar objects to a HashSet perfectly well. You just aren't adding them to the right HashSet. See this?



Here you declare a HashSet variable named money, but you don't assign it a value. So it's null. Later in what appears to be a constructor, you do this:



Here you declare another variable named money and assign it a value. But it's a local variable whose scope is only within the constructor. It isn't the same as the class-level variable you declared earlier; that one remains null, and that's what you print later.

So what you should do is, don't declare a local variable in the constructor. Just use the class-level variable which is already declared. Like this:


 
Kayleigh Gilroy
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That did it, cannot believe I overlooked that. thanks very much!!!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!