The first is assigning a list to list
, only that this list will be based on array which is being used as a basis (meuArray
), then deep down list
is just a reference to the list.
The second does the same with the constructor argument, but the constructor of ArayList
has the function of copying the content it receives as a list, then it will take the received reference and copy each element to a new list, so it is much slower, but will have an isolated list.
The question is whether you want to keep the same list or not. The difference is in the constructor and not in the method asList()
. The first does not build anything, it just uses what was already built by asList()
, and this method usually does not build anything strong either, it even builds a list object, but it will reference the array directly and make no copy.
One difference is that
asList
returns a list that cannot have its size changed, so calladd
,remove
andclear
inlist
make an exception (java.lang.UnsupportedOperationException
), but inarrayList
no. If you will not use these methods, the decision factor becomes what Maniero comments in his answer below. And to know if it impacts on performance, just doing performance tests to know :-) (maybe for very large lists and/or with elements that occupy a lot of memory has a significant difference, but of qq way, just testing to know)– hkotsubo
That’s right @hkotsubo, it does not return the class
java.util.ArrayList
and yes the classjava.util.Arrays.ArrayList
– renanvm