I have two classes, Stock
and Crypto
. Both are subclasses of Security
, which is where they get the methods invoked below. I want a general method that accepts either one of these and adds or updates to the respective HashMap. Something like:
1 class Portfolio {
2 private HashMap<String, Stock> stocks;
3 private HashMap<String, Crypto> cryptos;
4
5 public void add(Security s) {
6 HashMap<String, ? extends Security> table;
7 if (s instanceof Stock)
8 table = stocks;
9 else if (s instanceof Crypto)
10 table = cryptos;
11 else
12 return;
13 if (table.containsKey(s.toString()))
14 table.get(s.toString()).addShares(s.getShares(), s.getAvgPrice());
15 else
16 table.put(s.toString(), s); //ERROR
17 totalEquity += s.getAvgPrice() * s.getShares();
18 }
19 }
I'm aware that only null can be put in a wildcard HashMap like this. I tried the helper method workaround described in the wildcard docs but I still get an error. I'd like to find a solution that doesn't require repeating lines 13-17 for the two subclasses since the only methods needed here are implemented by the superclass.