Reputation: 7678
The following code will not compile
import java.util.List;
class Scratch {
public static void main(String[] args) {
Foo<Object> foo = new Foo<>();
Bar bar = new Bar();
bar.bar(List.of(foo)); // Okay
List<Foo<Object>> foos = List.of(foo);
bar.bar(foos); // Error
}
static class Foo<T> {}
static class Bar {
void bar(List<Foo<?>> foos) {}
}
}
The line bar.bar(foos);
casese this error:
incompatible types: java.util.List<Scratch.Foo<java.lang.Object>> cannot be converted to java.util.List<Scratch.Foo<?>>
Why are the types incompatible when the List<Foo<?>>
is constructed outside bar()
method call?
Upvotes: 1
Views: 145
Reputation: 141
You might also use a generic type in the method signature other than wildcard, that also still allows any Object type i.e below:
<T> void bar(List<Foo<T>> foos)
instead of
void bar(List<Foo<?>> foos)
Upvotes: 0
Reputation: 18245
You should fix the <?>
, because Foo<?>
and Foo<Object>
are not the same.
void bar(List<Foo<Object>> foos) {}
Upvotes: 1