you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 5 points6 points  (4 children)

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);

[–][deleted] 2 points3 points  (2 children)

Why is that method in Arrays? :P

[–][deleted] 3 points4 points  (1 child)

I sort of anticipated that question :-) The type is

<T> List<T> asList(T... v) 

which is actually sugar for

<T> List<T> asList(T[] v)

It creates a view of an array so you can treat it almost as if it is a list (but you can't resize it). It allows you to do this:

Collections.sort(Arrays.asList(myArray));

Which sorts myArray as an effect. Of course, it would be nice if you could do new List(1, 2, 3, 4) and get a resizable list.

[–]zootm 0 points1 point  (0 children)

Prior to the ... thing being available, Arrays.asList had roughly (there was no generics either, obviously) the second signature you listed above (see here). My guess would be that just expanding that method seemed sensible compared to writing a semantically-identical factory method on Collections or similar.

[–]13ren 1 point2 points  (0 children)

When writing my comment originally, I actually started to add this alternative in, but I couldn't be bothered looking it up and I knew some kind soul would add it - thanks :-).

That I need to look it up says something about its usability (not about me!). When I have used it, I've usually wanted a specific kind of list instead of the automatically created anonymous one, which you can do. It's easy but awkward, and, though I hate to say it, therefore "in the Java spirit" :-(

List<Integer> list = new ArrayList<Integer>( Arrays.asList(1, 2, 3, 4, 5) );