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);
Java SE 1.5.0
int[] numbers = new Integer[] { 1, 2, 3 }; java.util.List<Integer> list = Arrays.asList(numbers);
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);
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);
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!