Skip to main content
added 5 characters in body
Source Link
JB Nizet
  • 694.2k
  • 94
  • 1.3k
  • 1.3k

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 to addfrom adding anything to the list though:

List<?> query() { // equivalent of List<? extends Object> ... return listOfListOfString; } 

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 to add anything to the list though:

List<?> query() { // equivalent of List<? extends Object> ... return listOfListOfString; } 

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; } 
Source Link
JB Nizet
  • 694.2k
  • 94
  • 1.3k
  • 1.3k

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 to add anything to the list though:

List<?> query() { // equivalent of List<? extends Object> ... return listOfListOfString; }