Home > Java > javaTutorial > Why Doesn't Arrays.asList() Work with Primitive Arrays?

Why Doesn't Arrays.asList() Work with Primitive Arrays?

DDD
Release: 2025-01-03 07:06:39
Original
703 people have browsed it

Why Doesn't Arrays.asList() Work with Primitive Arrays?

Arrays.asList() and Primitive Arrays

When attempting to convert an array of primitive data into a list using the Arrays.asList() method, one may encounter inconsistencies. This article explores the issue and provides solutions.

Problem Explanation

The Arrays.asList() method accepts variable arguments that represent an array. However, it does not support primitive data types such as int[], unlike reference types like Integer[]. As a result, the second example provided:

int[] ints = new int[] {1,2,3,4,5};
List<Integer> list = Arrays.asList(ints);
Copy after login

returns a List, not a List.

Autoboxing

Autoboxing, which converts primitive data types to their wrapper counterparts, does not apply to arrays of primitives. Hence, the int[] array is not automatically converted to an Integer[] array.

Solution

To resolve this issue, one can leverage third-party libraries such as Guava's com.google.common.primitive.Ints.asList method. It creates a list of boxed values from a primitive array. Alternatively, one can manually create an Integer[] array and assign values from the int[] array, i.e.,

int[] ints = new int[] {1,2,3,4,5};
Integer[] integers = new Integer[ints.length];
for (int i = 0; i < ints.length; i++) {
    integers[i] = ints[i];
}
List<Integer> list = Arrays.asList(integers);
Copy after login

The above is the detailed content of Why Doesn't Arrays.asList() Work with Primitive Arrays?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template