Java Arrays asList(int)

2021-6-4 anglehua

While doing simple program I noticed this issue.

int[] example = new int[10]; List exampleList = Arrays.asList[example];// Compilation error here

Compilation error is returned as cannot convert from List to List. But List is not permitted in java so why this kind of compilation error?

I am not questioning about autoboxing here I just wondered how Arrays.asList can return List.

asList implementation is

public static List asList[T... a] { return new ArrayList[a]; }

So it is treating int[] as T that is why this is happening.

There is no automatic autoboxing done of the underlying ints in Arrays.asList.

  • int[] is actually an object, not a primitive.

  • Here Arrays.asList[example] returns List. List is indeed invalid syntax.

  • You could use:

    List exampleList = Arrays.asList[ArrayUtils.toObject[array]];

    using Apache Commons ArrayUtils.

Arrays.asList[...] works perfectly to transform an array of objects into a list of those objects.

Also, Arrays.asList[...] is defined in Java 5 with a varag construct, or, in order words, it can accept an undefined number of parameters in which case it will consider all of those parameters as members of an array and then return a List instance containing those elements.

List objList = Arrays.asList[obj1, obj2, obj3];

That means you can create a list with a single element:

List objList = Arrays.asList[obj1];

Since List is not permitted in Java, when you use a int[] array as parameter for Arrays.asList it will consider it as the single element of a list instead of an array of int. That's because arrays are objects by themselves in Java while an int [and any other primitive] is not.

So, when converting an array of primitives, Arrays.asList will try to return a list of primitive arrays:

List intArrayList = Arrays.asList[new int[]{ 1, 2, 3 }];

采集自互联网,如有侵权请联系本人

I once asked this question to one of the Java developers during an Interview and like many others, he answered that Arrays.asList[] can convert an array of primitive integer values to ArrayList in Java, which was actually wrong. Even though, Arrays.asList[] is the go-to method to convert an Array to ArrayList in Java when it comes to converting a primitive array to ArrayList, this method is not useful. The Arrays.asList[] method does not deal with boxing and it will just create a List which is not what you want. In fact, there was no shortcut to convert an int[] to ArrayList or long[] to ArrayList till Java 8.

From JDK 8 onwards, you either had to make a utility method or need to use general-purpose Java libraries like Google Guava or Apache Commons to convert an array of primitive values. byte, short, char, int, long, float, and double to ArrayList of Byte, Character, Short, Integer, Long, Float, and Double wrapper classes.

Though from Java 8 onwards, you can use the java.util.Stream to convert an int[] to ArrayList. There are specialized stream implementations for primitive data types like IntStream for primitive int, LongStream for primitive long, and DoubleStream for primitive double, which can convert an array of primitive values to a stream of primitive values.

Once you get the Stream of int values, you can use the boxed[] method to convert it to Stream of Integer wrapper objects. After that you can just convert Stream to List as shown in that article i.e. you can use the collect[] method of the stream with Collectors.toList[] to get a list.

If you want ArrayList instead of List then you can pass a Supplier to Collectors, which will accumulate elements into an ArrayList as shown below: int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17}; ArrayList list = IntStream.of[primes] .boxed[] .collect[Collectors.toCollection[ArrayList::new]]; Alternatively, you can also use the copy constructor of the Collection interface to create an ArrayList by copying all elements from the List instance as shown in the following example: List list = IntStream.of[primes] .boxed[] .collect[Collectors.toList[]]; ArrayList arraylist = new ArrayList[list];

What is this code doing? Well, if you are not very familiar with Java 8, Stream, and method reference then here is a step by step explanation of the above one-liner of converting a primitive array to ArrayList in JDK 8:

1] The IntStream.of[primes] is converting an int array to an IntStream object.

2] The boxed[] method of IntStream convert applies boxing on each element of IntStream and returns a Stream of Integer i.e it converts IntStream to Stream object.

3] The collect[] method collects all elements of Stream into any Collection class by using Collectors of Java 8. A Collector encapsulates the functions used as arguments to collect[Supplier, BiConsumer, BiConsumer], allowing for reuse of collection strategies and composition of collect operations such as multiple-level grouping or partitioning.

4] The Collectors.toCollection[] method collects elements of Stream into a Collection which is specified by the first parameter. Here we are passing ArrayList::new which is a constructor reference, which means all elements of Stream will be collected into an ArrayList. See The Complete Java MasterClass to learn more.


By far, That was the simplest way to convert an array of primitive data types to a List of wrapper objects like an array of ints to ArrayList of Integers.

Btw, there is another way to convert a primitive array to ArrayList in Java 8 by using the Arrays.stream[] method, which converts an array to Stream in Java 8. 

This method is equivalent to IntStream.of[int[]] and return an IntStream. The rest of the code will remain the same i.e. you can use the following one-liner to convert an int[] to ArrayList in JDK 8: ArrayList list = Arrays.stream[ints] .boxed[] .collect[Collectors.toCollection[ArrayList::new]]; Here is the full Java program to convert an int[] to ArrayList in Java 8: import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import java.util.stream.IntStream; public class Main { public static void main[String[] args] throws Exception { int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17}; System.out.println["primitive int array: " + Arrays.toString[primes]]; ArrayList listOfInts = IntStream.of[primes] .boxed[] .collect[Collectors.toCollection[ArrayList::new]]; System.out.println["ArrayList : " + listOfInts]; long[] numbers = new long[]{202, 3003, 2002, 3003, 222}; ArrayList listOfLong = Arrays.stream[numbers] .boxed[] .collect[Collectors.toCollection[ArrayList::new]]; System.out.println["primitive long array: " + Arrays.toString[numbers]]; System.out.println["ArrayList : " + listOfLong]; } } Output: primitive int array: [2, 3, 5, 7, 11, 13, 17] ArrayList : [2, 3, 5, 7, 11, 13, 17] primitive long array: [202, 3003, 2002, 3003, 222] ArrayList : [202, 3003, 2002, 3003, 222]
From the output, it's clear that both ways of converting an array of primitive values to ArrayList of objects work fine. You can use whatever you want.  See From Collections to Streams in Java 8 Using Lambda Expressions to learn more.

If you are not running in Java 8 and want to convert int[] to ArrayList on an earlier version of Java, like JDK 6 and JDK 7, then you have two choices, either use Google's Guava or Apache commons library as shown here or write your own conversion method as shown below: public class Main { public static void main[String[] args] throws Exception { int[] primes = new int[]{2, 3, 5, 7, 11, 13, 17}; System.out.println["primitive int array: " + Arrays.toString[primes]]; ArrayList listOfInts = new ArrayList[primes.length]; for[int i: primes]{ listOfInts.add[i]; } System.out.println["ArrayList : " + listOfInts]; } } Output primitive int array: [2, 3, 5, 7, 11, 13, 17] ArrayList : [2, 3, 5, 7, 11, 13, 17]
The code is pretty simple and self-explanatory. We are iterating over ArrayList using enhanced for loop of Java 5 and adding each int value from array to ArrayList. When you add, Java uses autoboxing to convert an int value to an Integer object, so in the end, you have an ArrayList of Integer. Though, you can also use other ways to loop over an array,  like by using for or while loop. One slightly important thing to note is initializing ArrayList with the length of the array. This prevents ArrayList from being resizing multiple times. If you remember, by default ArrayList initializes with 10 elements and then keeps resize when it is about to fill, I guess when the load factor grows up to 0.75 it resizes and doubles itself. This involves a lot of array copy, which can slow down your application.

It's also a Java collection best practice to provide size while creating an instance of any Collection class like ArrayList. See these Java Performance courses for more such tips.

That's all about how to convert an int[] to ArrayList in Java. You can use this technique to convert any primitive array to ArrayList of respective wrapper class like you can convert a long[] to ArrayList, a float[] to ArrayList, a double[] to ArrayList, a char[] to ArrayList, a short[] to ArrayList, and a byte[] to ArrayList in Java.

Related Java 8 Tutorials

If you are interested in learning more about the new features of Java 8, here are my earlier articles covering some of the important concepts of Java 8:
  • How to join String in Java 8 [example]
  • How to use forEach[] method in Java 8 [example]
  • How to use filter[] method in Java 8 [tutorial]
  • 5 Books to Learn Java 8 from Scratch [books]
  • Java 8 - Stream.collect[] Example [example]
  • How to use Stream class in Java 8 [tutorial]
  • What is the double-colon operator of Java 8? [tutorial]
  • How to join String in Java 8 [example]
  • 20 Examples of Date and Time in Java 8 [tutorial]
  • 10 Free Courses for Experienced Java Programmers [courses]
  • How to use peek[] method in Java 8 [example]
  • Java 8 Stream.findFirst[] + filter[] example [see]
  • How to sort the may by values in Java 8? [example]
  • How to convert List to Map in Java 8 [solution]
  • Difference between abstract class and interface in Java 8? [answer]
  • How to use peek[] method in Java 8 [example]
  • How to format/parse the date with LocalDateTime in Java 8? [tutorial]
  • 5 Free Courses to learn Java 8 and 9 [courses]

Thanks a lot for reading this article so far. If you like this article then please share it with your friends and colleagues. If you have any questions or feedback then please drop a comment.

P. S. - In general, you should use Stream if you are using Java 8, it's cleaner than the Java 6 approach and also takes just one line to convert a primitive array to ArrayList. If you don't know much about Stream and Java 8, I suggest you read a good book on Java 8 to learn more about IntStream and other Stream features like Java 8 in Action.

Video liên quan

Chủ Đề