Container of Generic Types in java

Posted by Cyker on Stack Overflow See other posts from Stack Overflow or by Cyker
Published on 2013-06-30T16:05:53Z Indexed on 2013/06/30 16:21 UTC
Read the original article Hit count: 149

Filed under:

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.

© Stack Overflow or respective owner

Related posts about java