简体   繁体   中英

Problems with Java generics

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> ?

As you've said, any ArrayList<T> is a List<T> . But the opposite is not true: a List<T> is not always an ArrayList<T> .

This means that if the method readAllLines is returning a List<T> , then you can assign the value to a List<T> variable, not any of its subtypes without an explicit downcast (which should always be avoided).

I don't even see why you would want to downcast it to ArrayList<T> , the less you imply about a type, freer you are.

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 while a cast to ArrayList<String> 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));

In your example, you are doing a downcasting , ie you want to cast a parent class to a child class. This is very unsafe, since a child may offer more than a parent. In your example, an ArrayList has additional functionalities. Thus, to ensure safety, the compiler will never allow an implicit downcasting (but upcasting is ok, as a child has necessarily all the functionalities of a parent).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM