java - Why can't I add an object to a HashSet -


i trying populate hashset in constructor penny objects i'm not sure how this. have written keep getting error messages.

public pocket(int numofpennies){     hashset penniesset = new hashset<penny>();      while( penniesset.size() <= numofpennies){         penniesset.add(penny);   } 

you're not adding object set rather trying add type, , won't work or compile. instead of

penniesset.add(penny); 

try

// assuming penny has default constructor penniesset.add(new penny()); 

also,

  • add collection using loop, not while loop, since know prior starting loop how many times want loop.
  • are sure want use hashset hold pennies? hashsets used when want have no duplicates in collection, wouldn't 1 penny equivalent another? in other words, shouldn't true: pennya.equals(pennyb). of course depend on how define equals(...) , hashcode() penny class.
  • would different collection such arraylist more logical?

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -