问题
Arrays.asList
returns a typed List. But List is an interface so how can it be instantiated? If try and instantiated a typed List I get an error saying it is not possible.
Edit
Nevermind I see what's going on, just got confused by the docs for a moment.
回答1:
It's an Arrays.ArrayList
which shouldn't be confused with java.util.ArrayList
. It is a wrapper for the array which means any changes you make, alter the original array, and you can't add or remove entries. Often it is used in combination with ArrayList like
List<String> words = new ArrayList<>(Arrays.asList("Hello", "There", "World"));
回答2:
A List
can't be instantiated, sure. But you can instantiate a class which implements List
-- for example, an ArrayList
or LinkedList
, etc. These classes really are List
s. The point of returning a List
(the interface type) is that the method can return any object which implements the List
interface, and you shouldn't worry about exactly which concrete type it is.
回答3:
from class Arrays
public static transient List asList(Object aobj[])
{
return new ArrayList(aobj);
}
so when you execute Arrays.asList(...) you will take ArrayList which implements List. nobody will know that, except this one itself.
1 example
String[] array = new String[] {"one","two","three"}; List list = Arrays.asList(array);
来源:https://stackoverflow.com/questions/14093867/how-can-arrays-aslist-return-an-instantiated-list