• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why Arrays.asList over ArrayList()?  RSS feed

 
Eugen Milas
Greenhorn
Posts: 1
Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,


I'm a new member, sorry if this is a silly question..
I'm enrolled in a Java bootcamp and ever since we started learning about streams, my instructor keeps using Arrays.asList().

My question is.. what is the benefit of using it over ArrayList?
It looks to me like an ArrayList will do the job just fine and also provide the option of modifying the list if required.
Is this a performance thing or just a preference?


Thanks.
 
Junilu Lacar
Sheriff
Posts: 11486
180
Android Debian Eclipse IDE IntelliJ IDE Java Linux Mac Spring Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch!

I suspect it's more of a convenience thing. It's easier to initialize with a variable number of elements.
 
Maneesh Godbole
Bartender
Posts: 11445
18
Android Eclipse IDE Google Web Toolkit Java Mac Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch.

You are confusing two different things.
ArrayList is the concrete implementation of the List interface.
On the other hand Arrays#asList is a helper method to convert an array into a List

From the API docs
public static <T> List<T> asList(T... a)
Returns a fixed-size list backed by the specified array. (Changes to the returned list "write through" to the array.) This method acts as bridge between array-based and collection-based APIs, in combination with Collection.toArray(). The returned list is serializable and implements RandomAccess.
This method also provides a convenient way to create a fixed-size list initialized to contain several elements:

     List<String> stooges = Arrays.asList("Larry", "Moe", "Curly");


In other words, if you have String data[] (array) and you want a List<String> (list) Arrays.asList is the way to go.
 
Winston Gutkowski
Bartender
Posts: 10575
66
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Eugen Milas wrote:I'm enrolled in a Java bootcamp and ever since we started learning about streams, my instructor keeps using Arrays.asList().

I'm intrigued that you say "ever since we started learning about streams", because this suggests that your tutor is using a List as an interim step to a Stream, which isn't necessary since an array can be converted directly to a Stream with Stream.of(array).

There are, however, many reasons to prefer a List over an array - just a few of which are:
  • A far richer API - including subList()s.
  • Greater flexibility.
  • Concurrency (if needed).
  • Data protection (if needed).
  • Reifability.
  • but none of them involve performance.

    Arrays will always be quicker (a lot quicker) than Lists for basic fetching and storing, just as using an int will almost always be quicker than using an Integer; but when that performance is measured in billionths of a second, do you really care?
    There may be rare cases when you do, but 99% of the time you don't; which is why you'll see this quotation a LOT:
    Donald Knuth wrote:Premature optimization [...] is the root of all evil.

    HIH

    Winston
     
    Campbell Ritchie
    Marshal
    Posts: 56540
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    Welcome again

    I am sorry, but I am going to be very naughty and go into cynical mode. It is because he has read Urma Fusco and Mycroft's book (an excellent book, by the way; I have a copy). They use that construct frequently. There are several ways to create a Stream from an array:-
  • 1: Arrays.asList(...).stream().
  • 2: Add all elements to the List and then myList.stream(). Actually, that method is in the Collection interface.
  • 3: The of method of Stream
  • 4: The Arrays#stream(...) method.
  • Now, some of those methods are overloaded and some aren't.
    Arrays#asList isn't overloaded. So passing 1, 2, 3, 4, 5 causes that to be converted to an Integer[] which then turns into a List<Integer> (size=5). If you pass new int[]{1, 2, 3, 4, 5} however, that is one object, so you get a one‑element List<int[]>.
    Using ListCollection#stream() will give you a Stream<Object> like this:-Obviously you could have written List<Integer> instead, and you would have obtained a Stream<Integer>.
    Stream.of(1, 2, 3, 4, 5) creates a five‑element Stream<Integer> and Stream.of(new int[]{1, 2, 3, 4, 5}) creates a one‑element Stream<int[]>. Look at the two links for of, which show different overloadings of the method. The first one takes T... and the second T, so the T overloading takes precedence over the T... when you pass one argument.
    If on the other hand you try IntStream#of, you either get the version taking int..., which also accepts int[], and the version with one int parameter, both of which return an IntStream.

    If you really want overloadings, you find Arrays#stream(double[]) which returns a DoubleStream, Arrays#stream(int[]) which returns an IntStream, Arrays#stream(long[]) which returns a LongStream, and a version which takes arrays of T, probably every reference type returning a Stream<T>. I do not know whether you can pass any arrays of the other primitive types to Arrays#stream, but that appears to be the most versatile way to create a Stream from an array.

    Another thing about types of Streams. Boot Eclipse (it might work just as well with NetBeans or IntelliJ, but I have never tried), write something like:-Hover your mouse on each of the method names stream, mapToObj, map, collect and joining, and you will see a popup box with the type returned from those method calls and some javadoc information. Very useful
     
    Campbell Ritchie
    Marshal
    Posts: 56540
    172
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    A few minutes ago, I wrote:. . . I do not know whether you can pass any arrays of the other primitive types to Arrays#stream . . .
    I tried
    Arrays.stream(new byte[]{1, 2, 3, 4, 5})
    and got a compiler error that a byte[] cannot be applied to T[]. So pass int[]s long[]s and double[]s to stream, and no other kind of primitive arrays.
     
    Liutauras Vilda
    Sheriff
    Posts: 4917
    334
    BSD
    • Mark post as helpful
    • send pies
    • Quote
    • Report post to moderator
    ...my instructor keeps using Arrays.asList().

    My question is.. what is the benefit of using it over ArrayList?

    Haven't seen in which particular scenario he uses that, but that could be convenience thing initialising its elements, as Junilu actually already mentioned at the beginning.

    I might mistaken, but thinking that you're referring to the next situation.

    Consider two scenarios of initialising List:

    Clearly 1st scenario looks more neat when you know the elements beforehand.
     
    • Post Reply Bookmark Topic Watch Topic
    • New Topic
    Boost this thread!