problems with generic methods

106 views Asked by At

I am having problems with the following situation:

private static List<? extends Object> function1(final Collection<? extends Object>... collections) {
    final List<Object> result = new ArrayList<Object>();
    // do some work
    return result;
}


public static List<? extends Object> function2(final Collection<? extends Object>... collections) {
    // do some work
    return function1(collection);
}

On the last line the error is Type mismatch: cannot convert from Pair<String,List<capture#74-of ? extends Object>> to Pair<String,List<? extends Object>>

How can I define the generics right?

UPDATE: it should be possible to use different collection types in the call function1(Collection<Long>, Collection<String>)

1

There are 1 answers

0
Thomas W On BEST ANSWER

Your declarations don't imply that the parameter-type & return-type of "function2" are the same.

If the item-type in & out are common, you can declare:

public static <T>  List<T> function2 (Collection<T>... inputs) {
    // do some work
    return function1( inputs);
}

public static <T>  List<T> function1 (Collection<T>... inputs) {
    // do some work
}

Wildcard types with apparently similar ancestors are not necessarily assignable to each other, if their 'capture' is not necessarily from the same place or same type. This also protects from more-general assignments being used to add items of incorrect type.

For example, List<String> is not assignable to List<Object>, since Objects added to a String list would break code that expected only Strings in the list.

In general, <?> is a better shorthand for <? extends Object>. There may also apparently have been some bugs/ unnecessary warnings with writing it the long way.. See: https://bugs.java.com/bugdatabase/view_bug?bug_id=6480391

"collections" is a pretty poor to call your parameter, and using names/ keystrokes without meaning is an error. "inputs" is totally generic, but at least it tells you which way the parameter is going & distinguishes it clearly from "results".