Array to Arraylist conversion difference with "asList" and constructor

Asked

Viewed 200 times

2

What is the difference between these two ways of converting a array? If there is any difference, the same impact on performance?

List<String> list = Arrays.asList(meuArray);

ArrayList<String> arrayList = new ArrayList<String>(Arrays.asList(meuArray));
  • 1

    One difference is that asList returns a list that cannot have its size changed, so call add, remove and clear in list make an exception (java.lang.UnsupportedOperationException), but in arrayList 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)

  • 1

    That’s right @hkotsubo, it does not return the class java.util.ArrayList and yes the class java.util.Arrays.ArrayList

1 answer

3


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.

  • "The Arraylist constructor has the function of copying the content it receives as a list."This is in the specification or it is an implementation detail?

  • 1

    @Gabriel I don’t know because I haven’t seen the specification, I don’t know if it does, because this is not part of the language but of the library, so only the documentation of the standard implementation exists as a specification, and it is very bad giving room for interpretation. The fact is that it was made like this, so everyone who wants to be compatible has to do the same, no matter how it is implemented, the semantics must be data copy, at least in this constructor, there is no guarantee that another constructor is different, this is so. You can question it, but in practice it’s like this.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.