multiple datatypes in a list supporting generics in Java 1.5
How to support multiple datatypes when defining generic types for a list?
Thanks
How to support multiple datatypes when defining generic types for a list?
Thanks
Depending on your datatypes then there are many different alternatives... the generics tutorial advises against using <Object> it advises using <?> instead.
Alternatively if your datatypes have a parent class they all inherit from then you can use List<? extends ParentClass> so the list will then accept any class which is a child of the ParentClass
The full PDF document on generics is here: -
http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf
> > ... using <?> instead.
>
> Try adding something in such a List.
Hey I'm just saying what the Sun Generics tutorial advises...
Personally I try to avoid having multiple datatypes in a single list as much as possible.
> > > ... using <?> instead.
> >
> > Try adding something in such a List.
>
> Hey I'm just saying what the Sun Generics tutorial advises...
The tutorial probably meant to use the <?> in methods like this one for example:
public static void display(java.util.Collection<?> c) {
for(Object o : c) {
System.out.println(o);
}
}
Because you cannot do this:
java.util.Collection<?> c = new java.util.ArrayList<String>();
c.add("a String");
> Personally I try to avoid having multiple datatypes
> in a single list as much as possible.
Agreed!
> > > > ... using <?> instead.
> > >
> > > Try adding something in such a List.
> >
> > Hey I'm just saying what the Sun Generics tutorial
> advises...
>
> The tutorial probably meant to use the <?> in methods
> like this one for example:
> public static void
> display(java.util.Collection<?> c) {
> for(Object o : c) {
>System.out.println(o);
>}
> }
>
> Because you cannot do this:
> java.util.Collection<?> c = new
> java.util.ArrayList<String>();
> c.add("a String");
>
And because you cannot do this:
java.util.Collection<Object> c = new java.util.ArrayList<String>();
but of course you can do this:
java.util.Collection<Object> c = new java.util.ArrayList<Object>();
-Puce