Daniel Watson
Daniel Watson

Reputation: 13

Why can't I add an object to a HashSet

I am trying to populate a HashSet in the constructor with Penny objects but I'm not really sure how to do this. I have written this but I keep getting error messages.

public Pocket(int numOfPennies){
    HashSet penniesSet = new HashSet<Penny>();

    while( penniesSet.size() <= numOfPennies){
        penniesSet.add(Penny);


}

Upvotes: 0

Views: 4168

Answers (1)

Hovercraft Full Of Eels
Hovercraft Full Of Eels

Reputation: 285415

You're not adding an object to the set but rather are trying to add a type, and this won't work or even compile. Instead of

penniesSet.add(Penny);

try

// assuming Penny has a default constructor
penniesSet.add(new Penny());

Also,

  • Add to the collection using a for loop, not a while loop, since you know prior to starting the loop how many times that you want to loop.
  • Are you sure you want to use a HashSet to hold your pennies? HashSets would be used when you want to have no duplicates in your collection, but wouldn't one Penny be equivalent to another? In other words, shouldn't this always be true: pennyA.equals(pennyB). Of course this would depend on how you define equals(...) and hashCode() for your Penny class.
  • Would a different collection such as an ArrayList be more logical?

Upvotes: 5

Related Questions