如何使java函数获取任何类的对象列表

时间:2018-04-22 13:43:37

标签: java

我正在尝试编写一个Java函数,该函数需要List List任何类的对象,然后计算包含的对象的大小内部列表对象的所有不同组合,其中所有对象来自不同的列表。算法很简单:

int combos(List<List<Object>> inList) {
    int res = 1;
    for(List<Object> list : inList) {
        res *= list.size();
    }
    return res;
}

但是当我尝试使用List<List<Integer>>对象作为输入参数运行函数时,我收到此错误:

List<List<Integer>> input = new ArrayList<List<Integer>>();
input.add(new ArrayList<Integer>());
input.get(0).add(1);
input.get(0).add(2);
combos(input);

错误:

The method combos(List<List<Object>>) in the type SpellChecker is not applicable for the arguments (List<List<Integer>>)

据我了解,ObjectInteger的父类。那么为什么这不起作用呢?我怎样才能使它发挥作用?

4 个答案:

答案 0 :(得分:1)

ObjectInteger之间的关系不适用于List<Object>List<Integer>,例如, this related question了解更多详情。

使用类型参数:

<T> int combos(List<List<T>> inList) {
    int res = 1;
    for(List<T> list : inList) {
        res *= list.size();
    }
    return res;
}

答案 1 :(得分:1)

一种解决方案是在combos中使用类型参数:

<T> int combos(List<List<T>> inList) {
    int res = 1;
    for(List<T> list : inList) {
        res *= list.size();
    }
    return res;
}

答案 2 :(得分:1)

这与嵌套泛型的this question密切相关。该问题的答案提供了一些很好的信息。

除了你在这里得到的两个好答案之外,还有另外一个选择。

public static void main(String[] args) {
    List<List<Integer>> input = new ArrayList<>();
    input.add(new ArrayList<>());
    input.get(0).add(1);
    input.get(0).add(2);
    combos(input);
}

static int combos(List<? extends List<?>> inList) {
    int res = 1;
    for (List<?> list : inList) {
        res *= list.size();
    }
    return res;
}

答案 3 :(得分:-1)

如果您不需要将列表数据类型专门化为List<Integer>

,这也可以。
List<List<Object>> input = new ArrayList<List<Object>>();

input.add( new ArrayList<Object>() );

input.get( 0 ).add( new Integer(1) );
input.get( 0 ).add( new Integer(2) );


combos( input );