Home > Java > javaTutorial > How Do I Correctly Convert a Java Array to an ArrayList?

How Do I Correctly Convert a Java Array to an ArrayList?

Patricia Arquette
Release: 2024-12-14 05:01:15
Original
223 people have browsed it

How Do I Correctly Convert a Java Array to an ArrayList?

Converting Array to ArrayList in Java

In Java, the process of converting an array into an ArrayList can sometimes be confusing, especially when considering the changes introduced in Java SE 1.4.2. This article delves into the intricacies of this conversion, providing a comprehensive understanding of the available options.

Originally, the Arrays.asList() method allowed for the creation of an ArrayList containing the elements of an array. However, this behavior was modified in Java SE 1.5.0, leading to the ArrayList instead containing the array itself.

For instance, consider the following code snippets:

Java SE 1.4.2

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

Java SE 1.5.0

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

The notable difference lies in the type of ArrayList created. In 1.4.2, list is an ArrayList containing the Integer values 1, 2, and 3. In 1.5.0 , list is an ArrayList containing the array numbers.

This distinction can lead to unexpected results, such as:

Assert.assertTrue(list.indexOf(4) == -1);
Copy after login

While this assertion holds true in 1.4.2, it fails in 1.5.0 because list now contains the array numbers, not the Integer values.

To avoid such issues and obtain an ArrayList of Integer values, one solution is to use the Integer class that wraps the primitive int type:

Integer[] numbers = new Integer[] { 1, 2, 3 };
java.util.List<Integer> list = Arrays.asList(numbers);
Copy after login

By utilizing the Integer class, this conversion creates an ArrayList containing the desired Integer values.

The above is the detailed content of How Do I Correctly Convert a Java Array to an ArrayList?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template