Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

new ArrayList<T> (T[] arr)

Tags:

java

Okay So this doesnt make sense to me.... maybe someone can shed some light. A technique I figure out for converting primitive arrays into ArrayLists is as follows.

arr = new ArrayList<String>(Arrays.asList(primitveArray));

this works quit well. But today, I start wondering how efficent this was, since I happened to be writing some code where performance is more important then It had been in other applications I had worked on in the past and decided to look at the source code for Arrays.asList()

I found this:

public static <T> List<T> asList(T... array) {
    return new ArrayList<T>(array);
}

And I said to myself: "Im such an idiot, Its just passing the array into the ArrayList constructor ArrayList<T>(T[] arr), why dont I just skip a step and not use the stupid Arrays.asList?

So i try this

arr = new ArrayList<T>(primitveArray)

in my code. But then suddenly ArrayList<T>(T[] arr) is undefined. Im quite confused why this would be?

like image 772
gbtimmon Avatar asked Dec 15 '22 23:12

gbtimmon


1 Answers

But then suddenly ArrayList<T>(T[] arr) is undefined. I'm quite confused why this would be?

There are two classes named ArrayList:

  • one is a private static inner class of java.util.Arrays;
  • the other is java.util.ArrayList.

asList() uses the former. You are trying to use the latter. The two classes are unrelated, they just happen to share the same name.

It is important to note that java.util.Arrays.ArrayList does not copy the array. It provides a view onto it.

like image 67
NPE Avatar answered Dec 30 '22 18:12

NPE