Re: Help on java generics
Arne Vajh?j wrote:
Donkey Hot wrote:
Wow. Well I'll be damned, because I'm still with 1.4.2 with my day
work..:(
But still. TreeList does not "extend" List, it implements it. Generics
is hard. Maybe harder than C++ templates?
Possible, but safer to use.
Arne
Actually, its easier than C++ templates, and less safe to use :-)
C++ templates allow much more flexibility and expressiveness (you can
create a specialization, for example), but are therefor more complicated
and confusing.
Java Generics are simply extra run-time information that you can choose
to ignore at compile time, and therefor run the risk of runtime
ClassCastException (when used incorrectly), where C++ templates are
expressed and enforced at compile time, so you'll get a compiler error
isntead.
As for the OP's original question:
You probably want
List<List<String>> strings = new ArrayList<List<String>>();
strings.add(new ArrayList<String>());
Keep your interface as generic as possible. You might even consider
whether you truly need a List, or a Set, or even if you only care to
guarantee a Collection. A List should be used if ordering matters, a
Set if you don't want duplicates, and a Collection if the consumer
shouldn't care.
--
Daniel Pitts' Tech Blog: <http://virtualinfinity.net/wordpress/>