I have a list of lists:

List<List<Object>> listOfRowsData = new ArrayList<List<Object>>(); 

and static method that returns a list

 DBManager.getAllRecords(tableName, s) 

With the help of iteration I fill in the list:

 for(String s : columnArray) { listOfRowsData.add(DBManager.getAllRecords(tableName, s)); } 

The problem is that initially I wanted not

 List<List<Object>> listOfRowsData 

but

 List<List<String>> listOfRowsData 

But the compiler corrected me to List<List<Object>> listOfRowsData . Therefore, the question is actually - why?

  • one
    DBManager.getAllRecords probably returns a List<Object> - zRrr

1 answer 1

The String class inherits from the Object class, and you can write the following:

 List<Object> objList = new ArrayList<>(); objList.add(new String("string")); 

But this rule does not work when using generic programming. This means that List<String> not inherited from List<Object> , and if you use the overloaded add() method to add the list to another list, the compiler will generate an error (actually, what happened to you). If this were not the case, then we could easily break the uniformity of the list:

 List<List<Object>> objList = new ArrayList<List<String>>(); List<Object> intList = new ArrayList<>(); intList.add(new Integer(5)); objList.add(intList); 

As you can see, in this example we added a list of integer variables to the list of lists, which expects to store only string data.

If you need a list with the type List<List<String>> , you can get the result of the method DBManager.getAllRecords(tableName, s) , explicitly DBManager.getAllRecords(tableName, s) each of its elements to the type String and add to the list listOfRowsData .


Additional links:

  1. Generics, Inheritance, and Subtypes .
  2. Is the List a subclass of List? Why aren't Java's generics implicitly