HashMap中的Java有界类型参数

时间:2015-10-04 16:45:34

标签: java hashmap bounded-wildcard bounded-types

我正在学习如何使用通配符和有界类型参数。我想在传递HashMap的方法中使用(我认为)有界通配符。我已经看到了有界类型参数和有界通配符的例子,但是我还没有找到任何能告诉我如何将HashMap传递给HashMap可以包含不同值对象的方法的东西。

Map<Integer, Company>
Map<Integer, Employee>
Map<Integer, Location>

这就是我上面列出的第一张地图的例子:

public Map<Integer, Company> readXML(Map<Integer, Company> companies) {

我想使用以下内容来启用此方法来处理上面列出的任何一个地图。

public Map<Integer, ?> readXML(Map<Integer, ?> values) {

有人可以告诉我一个如何在此方法中使用通配符作为Map值的示例吗?

1)我是否需要创建一个扩展值对象(公司,员工,位置)的Map类?

2)或者有更好的方法来实现这一目标吗?换句话说,我做错了吗?

感谢您的建议。

1 个答案:

答案 0 :(得分:2)

由于您的方法readXML(Map<Integer, ?(V)> companies)可以接受公司,员工和位置类型的V。你可以用下面提到的方法解决这个问题。

  1. 您可以使所有提到的类扩展新类,也可以使其实现我们的自定义Type接口,并将该类型用于V

  2. 向您的方法添加其他参数,在调用api的同时向其发送Class信息。

    public <V> Map<Integer, V> readXML(Map<Integer, V> values, Class<V> clazz) {
        if(clazz == Integer.class) {
            ...
        } else if// or if all the class type has same implementation use the 
                 // || operator in the above if condition only. 
                ...
        //and finally
        else {
            // either throw **IllegalArgument/Unsupported operation** exception
            // for the type 'V' Or handle in any other way you like to implement
        }
    }
    

    最后,IllegalArgument / UnsupportedOperation exception是未经检查的例外。如果您决定抛出异常,请确保正确记录您的方法。