I understand this will not work because List is an abstract interface:
List<Integer> l = new List<>();
and this is why I have been using typically ArrayList<>.
I’m curious why the following is valid in assignment of an object to List<String> l:
ArrayList<E> al = new ArrayList<>();
List<String> l = al.stream().collect(Collectors.toList());
It was my understanding objects couldn’t be created from interfaces, only when they have been implemented. Can anyone explain why second code snippet works and how I should be understanding this difference?
>Solution :
Collectors.toList() will return you some concrete List instance. Maybe an ArrayList, maybe something else. All the API is willing to guarantee is that it conforms to the List interface.
The Javadoc explicitly states:
There are no guarantees on the type, mutability, serializability, or
thread-safety of theListreturned; if more control over the returned
Listis required, usetoCollection(Supplier).
You can check the specific type that is returned at runtime, but shouldn’t rely on it.