How the array as int [], converted into a Java List |The Java Debug notes

This article is participating in “Java Theme Month – Java Debug Notes Event”, see < Event link > for more details.

Lift to ask:

How do I convert an array to a List in Java?

I used arrays.aslist (), but the behavior (and signature) of this method changed from Java SE 1.4.2 (now archived) to 1.8, and most of the code snippets I found on the network used 1.4.2 behavior.

Such as:

int[] spam = new int[] { 1, 2, 3 };
Arrays.asList(spam);
Copy the code
  • Return a list of elements 1, 2, and 3 on 1.4.2
  • Returns the address of the list on 1.5.0+

In many cases, it should be easy to detect, but can sometimes be overlooked:

Assert.assertTrue(Arrays.asList(spam).indexOf(4) == -1);
Copy the code

Answer 1:

In your example, that happens because you don’t have a list of basic data types. In other words, it is impossible to get List

.

However, you can wrap int with Integer using List

:

Integer[] spam = new Integer[] { 1, 2, 3 };
List<Integer> list = Arrays.asList(spam);
Copy the code

See this code running in real time on IdeOne.com.

Answer 2:

In Java 8, you can use the stream method:

int[] spam = new int[] { 1, 2, 3 };
Arrays.stream(spam)
      .boxed()
      .collect(Collectors.toList());
Copy the code

Answer 3:

When it comes to conversion, it depends on why you need your List. If you just need to read the data. All right, you just have to do this:

Integer[] values = { 1, 3, 7 };
List<Integer> list = Arrays.asList(values);
Copy the code

However, if you do the following:

list.add(1);
Copy the code

You will get the exception: Java. Lang. UnsupportedOperationException. So, in some cases, you even need to do this:

Integer[] values = { 1, 3, 7 };
List<Integer> list = new ArrayList<Integer>(Arrays.asList(values));
Copy the code

The first method doesn’t actually convert an array, but rather “represents” it as a List. But an array has all its properties, such as a fixed number of elements. Note that the type ArrayList needs to be specified during construction.

The original link