将不同子类的插入泛化到各自的 HashMap
Generalizing the insertion of different subclasses to respective HashMaps
我有两个 类、Stock
和 Crypto
。两者都是 Security
的子 类,这是它们获取下面调用的方法的地方。我想要一个接受其中任何一个并添加或更新相应 HashMap 的通用方法。类似于:
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 }
我知道只能将 null 放入这样的通配符 HashMap 中。我尝试了通配符文档中描述的 helper method workaround 但我仍然收到错误消息。我想找到一个不需要为两个子 类 重复第 13-17 行的解决方案,因为这里唯一需要的方法是由超类实现的。
根据以上信息,我认为您可以做的最简单的事情是添加两个 public 方法(一个使用 Stock
,另一个使用 Crypto
)映射到推断子类型的通用私有 add
方法:
public void add(Stock s) {
add(s, stocks);
}
public void add(Crypto c) {
add(c, cryptos);
}
private <T extends Security> void add(T s, Map<String, T> map) {
map.put(s.getName(), s); //<-- put into the right map
//or do whatever you want with it
}
通过以上内容,您将能够执行以下操作:
portfolio.add(new Stock("APPLE")); //<-- compiler sends it to the add(Stock s) method
portfolio.add(new Crypto("BTC")); //<-- compiler sends it to the add(Crypto c) method
编译器将调度到正确的 public
方法,该方法将简单地选择正确的映射并将其传递给处理 T extends Security
的通用 private
add 方法。
我有两个 类、Stock
和 Crypto
。两者都是 Security
的子 类,这是它们获取下面调用的方法的地方。我想要一个接受其中任何一个并添加或更新相应 HashMap 的通用方法。类似于:
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 }
我知道只能将 null 放入这样的通配符 HashMap 中。我尝试了通配符文档中描述的 helper method workaround 但我仍然收到错误消息。我想找到一个不需要为两个子 类 重复第 13-17 行的解决方案,因为这里唯一需要的方法是由超类实现的。
根据以上信息,我认为您可以做的最简单的事情是添加两个 public 方法(一个使用 Stock
,另一个使用 Crypto
)映射到推断子类型的通用私有 add
方法:
public void add(Stock s) {
add(s, stocks);
}
public void add(Crypto c) {
add(c, cryptos);
}
private <T extends Security> void add(T s, Map<String, T> map) {
map.put(s.getName(), s); //<-- put into the right map
//or do whatever you want with it
}
通过以上内容,您将能够执行以下操作:
portfolio.add(new Stock("APPLE")); //<-- compiler sends it to the add(Stock s) method
portfolio.add(new Crypto("BTC")); //<-- compiler sends it to the add(Crypto c) method
编译器将调度到正确的 public
方法,该方法将简单地选择正确的映射并将其传递给处理 T extends Security
的通用 private
add 方法。