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.

2

2 Answers 2

5

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; } 
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.