Java泛型 - 将一个子类型的集合传递给一个需要基类型集合的方法 [英] Java generics - passing a collection of subtype to a method requiring a collection of base type

查看:157
本文介绍了Java泛型 - 将一个子类型的集合传递给一个需要基类型集合的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中执行此操作 - 将一个子类型的集合传递给需要基类型集合的方法?

下面的例子给出了:

 方法foo(Map< String,List>)不适用于参数(Map< String,MyList>)

我可以通过为类型化集合创建类层次结构来实现 - 但是否有可能?

  public void testStackOverflow(){
$ b $ class MyList extends AbstractList {
public Object get(int index){
返回null;
}
public int size(){
return 0;
}
};

地图< String,List> baseColl = null;
地图< String,MyList> subColl = null;

foo(subColl);

$ b $ private void foo(Map< String,List> in){
}

编辑:从答案中发现,这需要有界通配符,因此添加此文本以便搜索

解决方案

foo 更改为:

  private void foo (Map< String,?extends List> in){
}

你可以在 foo 中做什么,但这是合理的。您知道,您从地图中获取的任何值都是一个列表,但您不知道要将哪种值放入地图。


How to do this in Java - passing a collection of subtype to a method requiring a collection of base type?

The example below gives:

The method foo(Map<String,List>) is not applicable for the arguments (Map<String,MyList>)

I can implement by creating a class hierarchy for the typed collections - but is it possible otherwise?

public void testStackOverflow() {

    class MyList extends AbstractList {
        public Object get(int index) {
            return null;
        }
        public int size() {
            return 0;
        }           
    };

    Map <String, List>   baseColl = null;
    Map <String, MyList> subColl  = null;

    foo (subColl);              
}

private void foo (Map <String, List> in) {      
}

EDIT: Turns out from the answers that this requires "bounded wildcard" so adding this text for searchability

解决方案

Change foo to:

private void foo(Map <String, ? extends List> in) {
}

That will restrict what you can do within foo, but that's reasonable. You know that any value you fetch from the map will be a list, but you don't know what kind of value is valid to put into the map.

这篇关于Java泛型 - 将一个子类型的集合传递给一个需要基类型集合的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆