1

My code currently filling up a HashSet with an object of Class Coin.

private HashSet<Coin> walletcoin;
public Wallet(int WalletSize)
{
    walletcoin = new HashSet<Coin>();
    for(int i = 0; i < WalletSize; i++){
        walletcoin.add(new Coin());
    }
}

This seems to be working fine.

Class Coin:

public class Coin
{
    public Coin(){
    }    
}

The second method is currently trying to remove a Coin object from the HashSet.

public int removeCoin()
{
    Coin toremove = new Coin();
       if(walletcoin.contains(toremove))
       {    
           if(walletcoin.remove(toremove))
           {
               return 1;
           }

       }
       return 7;
}

I have created a new object of Class coin, to try to search against the HashSet. Currently after testing the program skips straight to the final return statement and does not go through the if statements.

How would I be able to modify my code in order for the if statements to correctly work, and remove one of the type Coin elements from the HashSet.

Pengoid
  • 35
  • 4
  • 4
    Tell us more about the `Coin` class! Does it have `equals` and `hashCode` overrides? – Sam Dec 14 '16 at 21:53
  • Just empty filler class, have edited into post. – Pengoid Dec 14 '16 at 21:56
  • 1
    Put this in real world terms. Put 5 coins in your wallet. Pull a 6th coin out of your pocket and hold it in your hand. Now find that 6th coin in your wallet. Doesn't make a whole lot of sense does it? – John3136 Dec 14 '16 at 21:56
  • You probably want to use a `List`. Otherwise, a `Set` will remove all duplicates, which means it will always hold 1 coin. – 4castle Dec 14 '16 at 21:57
  • @4castle you would need to provide a stronger argument for that claim. – Sam Dec 14 '16 at 21:58
  • Building on @John3136's comment, you should pass a `Coin` argument to your `removeCoin` method. That way, you might actually pass a `Coin` that exists in your wallet. When you say `new Coin()`, there is no chance that new coin is in your wallet. As a side note, I think that is a pretty bad duplicate flagging. What if he doesn't want to override equals and hashcode due to the simplicity of the program... – Adam Dec 14 '16 at 21:59
  • @John3136 The idea is you have 5 coins in your wallet, and then you use a coin so you go down to 4 coins – Pengoid Dec 14 '16 at 21:59
  • @Sam I'm basing my claim on what will happen once then override equals and hashcode. – 4castle Dec 14 '16 at 21:59
  • @4castle you're right, I hadn't thought of that. The coin would need to have some distinguishing features (a value, for example) in order for different coins to have different meaningful hash codes. – Sam Dec 14 '16 at 22:01
  • The coin is simply a coin, they will all be identical to each other – Pengoid Dec 14 '16 at 22:03
  • 1
    @Pengoid In that case there's no need for using a collection. Just use an integer for the number of coins. – 4castle Dec 14 '16 at 22:06

0 Answers0