0

The java documentation explains the difference between using Object as a type parameter and using and unbounded wildcard (?) by using the following code example:

    public static void printList(List<Object> list) {
        for (Object elem : list)
        System.out.println(elem + " ");
        System.out.println();
    }

and

public static void printList(List<?> list) {
    for (Object elem: list)
    System.out.print(elem + " ");
    System.out.println();
}

It says that the first example fails to achieve its goal of printing a list of any type. It can only print lists of Objects; it cannot print List<Integer>, List<String>, List<Double>, and so on, because they are not subtypes of List<Object>.

But surely Integer, String and Double are subtypes of Object? Doesn't everything inherit from Object in Java?

orrymr
  • 2,264
  • 4
  • 21
  • 29
  • 1
    The first example only fails to achieve its goal of printing a list of any type because you can't call it with a list of any type as a parameter. If you were to do some subversive casting, it'd work just fine, [as shown here](http://ideone.com/dWTCur). – Andy Turner Jul 21 '16 at 14:26
  • @AndyTurner Does _List objs = (List) (List) ints;_ First convert it to the raw List type, and thereafter to the parameterized List type? I've found that replacing that line with _List objs = (List) myList;_ also works – orrymr Jul 22 '16 at 09:54
  • 1
    Well, that works too, you're just keeping `objs` as a raw type, so the compiler will allow it as a parameter to any method expecting a generic list. I would advise making it a non-raw type, though, so that you have as much type checking as possible. – Andy Turner Jul 22 '16 at 10:32

0 Answers0