Hello! There is the following generalized method:

public static <T> List<T> getAllRecords(String table, String columnLabel) throws SQLException { List<T> list = new ArrayList<T>(); rs = stmt.executeQuery("SELECT * FROM " + table); while(rs.next()) list.add((T)rs.getString(columnLabel)); return list; } 

Here on this line

 list.add((T)rs.getString(columnLabel)); 

compiler swears

Signals places where an unchecked warning is for example:

 void f(HashMap map) { map.put("key", "value"); } 

Hint: Pass -Xlint: unchecked to javac to get more details.

That is, it (the compiler) means that there is an unchecked conversion. Can you tell what exactly is happening in the mentioned line and how will it be more correct to write the code? As I understand it, a conversion to a type that does not exist, therefore he swears ...

  • 2
    The compiler doubts that the type String can be cast to type T If T were a normal type, one could reassure the compiler by adding a check using instanceof . In your case, you just need to remove the declaration T and return List<String> , because resultSet.getString returns strings and so. Or do you want to write a method that returns a column from a table of the desired type? - zRrr
  • It just became interesting) In principle, yes, and so the String is returned. Is there an idea how convenient it is to return a column from a table of the desired type? - Igor Gorbunov
  • one
    If in Java 8, then you can pass to the lambda method or method reference, which will get the result from the set result with the desired type ( pastebin.com/JsRhNsDX ), it should work, but I did not check. - zRrr
  • The compiler does not have the ability to check which type is in T when compiling, and the virtual machine does not have the ability to check it during execution. Therefore, inside a parameterized class, you cannot create objects of type T , check whether the type of an object is T and perform similar operations. It is possible to cast objects to type T (compilation errors will not happen) - but it is pointless. In fact, the compiler cannot verify the compatibility of type T and the type of object passed. The compiler warns you about this - fedotsoldier

0