Re: Generic Trouble
On 11/12/2010 09:30 PM, Andreas Leitgeb wrote:
Stefan Ram<ram@zedat.fu-berlin.de> wrote:
Arne Vajh??j<arne@vajhoej.dk> writes:
Why not use<T> in the interface?
First of all, the generic class will *not* know the actual
type used. At most you can enforce it to be a subclass or
superclasses of some given class.
So let's assume that in your method you're going to deal with
type Number (which subclasses Object and is subclassed e.g. by
Integer):
Now, it depends on what you want to do with the Collection that
you're going to pass to that method:
- access elements *FROM* it:
use<T extends Number>, as that will allow
Collection<Number> but also Collection<Integer>
instances to be used.
- add (or overwrite) elements *TO* it:
use<T super Number>, as it is perfectly legal to write
objects that are known to be at least Numbers either to
a Collection<Object> as well as to a Collection<Number>
- do both of these above:
use Collection<Number>. Nothing else would allow for both
reading and writing Numbers.
And now, I guess, someone will come up and correct me in all those
points, where I decided to keep it simple to the point of omission
of some accuracy.
Looks correct from here.
Another point is that the <?> dodge works well for parameters to methods, but
not so well for returns from methods or member variable types.
The symptom the OP describes is a manifestation of incomplete type analysis.
The attempt to use a simplistic rule of thumb, like "always avoid raw types
with <?>", leads to such incomplete analysis. Unfortunately, to analyze types
down to where generics stop whing is to analyze them down to where you have
delineated all the type constraints completely. This is hard, especially when
you haven't yet gotten used to type analysis and type assertions, but it gets
a little better once you make the cognitive shift.
Don't think of generics as a way to eliminate warnings. If that's all you
need, just use raw types and '@SuppressWarnings("unchecked")'. Who needs all
that high-falutin' type safety anyway?
If you do need type safety, the good news is that a complete type analysis
reflects quite neatly as generics assertions in your Java code, and you will
have locked the door against all kinds of sneaky and
hard-to-diagnose-at-runtime bugs. I assess that the difficulty of generics is
precisely the difficulty of a complete type analysis. Thank goodness the
source records and the compiler enforces the results of that analysis.
--
Lew