Reputation: 5877
Given:
class Foo {
...
}
class Bar<T extends Foo> {
...
}
Assuming I want to make a list of instances of Bar
, with any generic type for Bar
allowed, the type of that list could be one of two options:
List<Bar<?>>
List<Bar<? extends Foo>>
1) I'd assume that these lists can contain the exact same objects, namely instances of Bar of any generic type. Is this true?
2) Which type is preferred? Should I be more explicit and restate the bound on the generic type of Bar
(second option), or just opt for a wildcard that is unbounded in the list, with the guarantee that instances of Bar
can only be constructed with a certain bound on the generic type before being put into the list (first option)?
Upvotes: 2
Views: 54
Reputation: 29680
1) I'd assume that these lists can contain the exact same objects, namely instances of Bar of any generic type. Is this true?
Both lists can only contain Bar<T>
where T
is either Foo
or any of its children.
2) Which type is preferred?
Both are equivalent in this case. However, reading code is more important than writing it; users might think "Oh, it's an unbounded wildcard, so I can use any type.", but they'd be wrong due to the bounded wildcard of Bar
. For that reason, the latter may be preferred in some cases, but at the end of the day, it's your call.
Upvotes: 1