Say you have some class with type T
:
class MyClass<T extends SomeOtherClass> {
....
}
Now, you want to store instances of this class into a collection, but you don't really care about the type. I would express this as following:
private final List<MyClass> entries = new ArrayList<>();
Is there any good reason/advantage to write the following instead?
private final List<MyClass<?>> entries = new ArrayList<>();
Or even:
private final List<MyClass<? extends SomeOtherClass> entries = new ArrayList<>();
I myself can only find a bad reason to do this: whenever the type definition of MyClass
changes (for example addition of another type), you have to alter the List<MyClass<?>>
or List<MyClass<? extends SomeOtherClass>>
definitions all over your code as well.
update
To update my question:
Why isn't the compiler to be able to track the type(s) of MyClass
when your write List<MyClass>
(or even List<MyClass<? extends SomeOtherClass>>
)? He knows that MyClass
is defined as MyClass<T extends SomeOtherClass>
, so why isn't he able/allowed to do that when you write List<MyClass>
?
In other words, why is List<MyClass>
not equal to List<MyClass<?>>
(or even List<MyClass<? extends SomeOtherClass>>
)? The compiler has all the information to make that conclusion himself, afaik.