Pradeep Pillai
Pradeep Pillai

Reputation: 95

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

Upvotes: 0

Views: 85

Answers (3)

Seb T
Seb T

Reputation: 902

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));

Upvotes: 4

Jack
Jack

Reputation: 133567

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.

Upvotes: 4

Derlin
Derlin

Reputation: 9891

In your example, you are doing a downcasting, i.e. 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).

Upvotes: 1

Related Questions