• 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

Referencing objects in a set.

 
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I'm placing a large number of Star objects in a hashset container. I want to be able to reference and remove a particular Star from that set at some later date, but I have no references for individual stars in the code below. How does one reference a particular element of the hashset without explicitly naming it during instantiation?



I could create a single star using Star sirius = new Star(), which would allow me to type hset.remove(sirius) above. But I have 1,000 stars to create and the names will be read randomly from a file.

Thank you for your help!
 
Bartender
Posts: 4179
22
IntelliJ IDE Python Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The ability to remove from a Set depends on the Object's definition of equality. For a HashSet, that would come to the combination of the Object's hashCode() and equals() methods.

So, if your Star Object has internal data which makes it unique, and you properly override the hashCode and equals methods, then you could create a NEW Star object from the same data and use that new Star to remove the old one.

For example


If your Star does have internal data, but you haven't overriden the hashCode() and equals() methods, then you should go do that.
See this, this, and this.

If the Star object does not have internal data that identifies it, then you are out of luck. In this case, your only solution would be to use a HashMap instead of a HashSet, and use the key you used to store the Star to later remove it.
 
Don't get me started about those stupid light bulbs.
reply
    Bookmark Topic Watch Topic
  • New Topic