2019-10-09
Problems with Java generics
stackoverflow
Question
ArrayList<String> list = new ArrayList<String>();
list = (ArrayList<String>) Files.readAllLines(FilePath);

In the above code, if I remove the explicit casting in second line, the compiler gives an error. Why is this explicit cast required considering the fact that Files.readAllLines(FilePath) returns a List<String>, and ArrayList<String> implements List<String> ?

Answer
1

The method Files.readAllLines() only guarantees to return an object of type List<String>, but not of the more specific type ArrayList<String>. The actual implementation type of the returned list may vary between different JDK implementations (they just need to be sub-classes of List<String>, so you while your cast may work in your environment with your JDK implementation it may not work in another.

If you really need your list to be an ArrayList, you can use this code instead:

ArrayList<String> list = new ArrayList<String>();
list.addAll(Files.readAllLines(FilePath));
Problems with Java generics
See more ...