1
public List<Object> query(){

        List<Object> listToReturn = new ArrayList<Object>();  
        List<String> listOfString = new ArrayList<String>();
        List<List<String>> listOfListOfString = new ArrayList<List<String>>();

        listOfListOfString.add(listOfString);
        listToReturn.add(listOfListOfString);

        return listToReturn;
    }

Instead of above method if I write :

public List<Object> query(){

        List<Object> listToReturn = new ArrayList<Object>();    
        List<String> listOfString = new ArrayList<String>();
        List<List<String>> listOfListOfString = new ArrayList<List<String>>();

        listOfListOfString.add(listOfString);

        return listOfListOfString;

    }

I get a compile-time error, Type mismatch: cannot convert from List<List<List<String>>> to List<Object>

I am a bit confused.

Alexis C.
  • 87,500
  • 20
  • 164
  • 172
Sandbox
  • 7,530
  • 11
  • 50
  • 66

2 Answers2

4

Is List<Object> a supertype of List<String>?

No, different instantiations of the same generic type for different concrete type arguments have no type relationship. FAQ102

The error Type mismatch: cannot convert from List<List<List<String>>> to List<Object> means that both objects has different concrete parameterized type.

What is a concrete parameterized type?

An instantiation of a generic type where all type arguments are concrete types rather than wildcards. FAQ101

More:

Source: Java Generics FAQs - Generic And Parameterized Types

Community
  • 1
  • 1
MariuszS
  • 29,365
  • 12
  • 111
  • 149
4

If you could do that, the caller, which gets a List<Object>, would be able to add any kind of Object to the list, although it's been declared as a List<List<String>>. It would thus ruin the type-safety of the list:

List<List<String>> listOfListOfString = ...;
List<Object> listOfObjects = listOfListOfString;
listOfObjects.add(new Banana()); 
// now your list of lists of strings contains a banana: oops!

You can do the following, however, which would prevent the caller from adding anything to the list though:

List<?> query() { // equivalent of List<? extends Object>
    ...
    return listOfListOfString;
}
JB Nizet
  • 657,433
  • 87
  • 1,179
  • 1,226