简体   繁体   中英

How to make java function take a list of objects of any class

I'm trying to write a Java function which takes a List of List s holding objects of any class, and then calculates the size of the set consisting of all different combinations of inner list objects, where all objects come from different lists. The algorithm is simple:

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

But I'm getting this error when trying to run the function with a List<List<Integer>> object as input parameter:

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 error:

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

As far as I understand, Object is the parent class of Integer . So why doesn't this work? How can I make it work?

The relationship between Object and Integer does not apply to List<Object> and List<Integer> , see eg this related question for more details.

Use a type parameter:

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

One solution is to use a type parameter in combos :

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

This is closely related to this question about nested generics. The answer in that question provides some good info.

On top of the two good answers you already got here is another option.

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;
}

This also works, if you don't need to specialize the List Datatype as 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 );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM