I have a generic class Foo<T>
and parameterized types Foo<String>
and Foo<Integer>
. Now I want to put different parameterized types into a single ArrayList
. What is the correct way of doing this?
Candidate 1:
public class MMM {
public static void main(String[] args) {
Foo<String> fooString = new Foo<String>();
Foo<Integer> fooInteger = new Foo<Integer>();
ArrayList<Foo<?> > list = new ArrayList<Foo<?> >();
list.add(fooString);
list.add(fooInteger);
for (Foo<?> foo : list) {
// Do something on foo.
}
}
}
class Foo<T> {}
Candidate 2:
public class MMM {
public static void main(String[] args) {
Foo<String> fooString = new Foo<String>();
Foo<Integer> fooInteger = new Foo<Integer>();
ArrayList<Foo> list = new ArrayList<Foo>();
list.add(fooString);
list.add(fooInteger);
for (Foo foo : list) {
// Do something on foo.
}
}
}
class Foo<T> {}
In a word, it is related to the difference between Foo<?>
and the raw type Foo
.
Update:
Grep What is the difference between the unbounded wildcard parameterized type and the raw type? on this link may be helpful.
A Generic Version of the Box Class This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T. A type variable can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.
Generic containers are just containers that serve no special purpose. Mostly a style attribute is bounded to a generic container for specifying the rendering or using a CSS rule. The only generic containers are <div> and <span> .
Both ArrayList and vector are generic types.
Whenever you want to restrict the type parameter to subtypes of a particular class you can use the bounded type parameter. If you just specify a type (class) as bounded parameter, only sub types of that particular class are accepted by the current generic class. These are known as bounded-types in generics in Java.
List
represents a list with no type parameter. It is a list whose elements are of any type, e.g. the elements may be of different types. It's basically the same as List<Object>
.
Meanwhile, List<?>
represents a list with an unbounded type parameter. Its elements are of a specific, but unknown (before runtime), type. These elements all have to be from the same type at Runtime.
I recommend avoiding using raw types. The proper solution for your example is List<Foo<?>>
.
You want to avoid raw types whenever possible. The correct way to do it would be with List<Foo<?>>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With