• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Adding class objects to a HashSet

 
Greenhorn
Posts: 6
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!

 
Marshal
Posts: 28193
95
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
That did it, cannot believe I overlooked that. thanks very much!!!
 
Are you here to take over the surface world? Because this tiny ad will stop you!
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic