How can Arrays.asList return an instantiated List?

扶醉桌前 提交于 2020-01-11 11:31:51

问题


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 Lists. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!