Re: ArrayList called with specific object constructors
On 28.04.2009 18:14, Lew wrote:
Zio Jerry wrote:
Anyway, your code seems pretty good but I have just a simple question:
why using "<? extends T>" instead of simply "<T>" ?
The difference is that a 'List<T>' can contain many different subtypes
of 'T' in it, e.g., a 'List<Number>' can contain a mix of 'Double',
'BigInteger' and 'AtomicLong' instances. A 'List<? extends T>' can
contain only one type of entry, which must be a subtype of 'T'. Thus,
a 'List<? extends Number>' could contain all 'Double' entries, or all
'BigInteger' entries, but not both in the same list.
Just a small note: Josh used the <? extends T> on the _factory_ and not
the _list_. Of course, the same reasoning as presented applies.
The reason to do it is greater flexibility, i.e. - translating the
example - not only factories with return type Number on the factory
method can be used but also factories for Integer, Double etc.
Read the sample chapter of Joshua Bloch's /Effective Java/ that covers
generics:
<http://java.sun.com/docs/books/effective/generics.pdf>
And one remark to the usage: with Josh's code you can nicely use an
anonymous class, e.g.
List<Foo> lst = makeList(new Factory<Foo>() {
Foo makeObject(String s1, String s2) {
return new Foo(s1, s2);
}
});
Whether that's reasonable or efficient depends of course on the context.
Kind regards
robert