In Java, you can create an ArrayList
from an array using the Arrays.asList()
method combined with the ArrayList
constructor. Here’s how to do it:
Method 1: Using Arrays.asList()
This is the simplest and most common approach.
import java.util.ArrayList;
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
// Example array
String[] array = {"Apple", "Banana", "Cherry"};
// Convert array to ArrayList
ArrayList<String> list = new ArrayList<>(Arrays.asList(array));
System.out.println(list); // Output: [Apple, Banana, Cherry]
}
}
Explanation:
Arrays.asList(array)
wraps the array into a fixed-size list backed by the array.new ArrayList<>(...)
converts the fixed-size list into a resizableArrayList
.
Method 2: Using Java 8 Streams (Flexible)
For more control (e.g., filtering/modifying elements):
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
String[] array = {"Apple", "Banana", "Cherry"};
// Convert array to ArrayList using streams
ArrayList<String> list = Arrays.stream(array)
.collect(Collectors.toCollection(ArrayList::new));
System.out.println(list); // Output: [Apple, Banana, Cherry]
}
}
Method 3: Manual Iteration (Legacy Approach)
For explicit control over element addition:
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
String[] array = {"Apple", "Banana", "Cherry"};
ArrayList<String> list = new ArrayList<>();
for (String element : array) {
list.add(element);
}
System.out.println(list); // Output: [Apple, Banana, Cherry]
}
}
Key Notes:
- Primitive Arrays:
Arrays.asList()
works with object arrays (e.g.,String[]
,Integer[]
), not primitive arrays (e.g.,int[]
).
For primitive arrays likeint[]
, use a loop or Java 8 streams:
int[] intArray = {1, 2, 3};
ArrayList<Integer> intList = new ArrayList<>();
for (int num : intArray) {
intList.add(num); // Autoboxing to Integer
}
- Mutability:
The list fromArrays.asList()
is fixed-size (you can’t add/remove elements). Usenew ArrayList<>(Arrays.asList(...))
to create a mutable list. - Shallow Copy:
TheArrayList
and the original array share references to the same objects. Changes to objects in one will reflect in the other.
Comparison
Method | Pros | Cons |
---|---|---|
Arrays.asList() | Simple, concise | Fixed-size unless wrapped in ArrayList |
Java 8 Streams | Flexible (filter/modify elements) | Verbose for simple cases |
Manual Iteration | Works for primitive arrays | More code |
When to Use Which:
- Most cases: Use
new ArrayList<>(Arrays.asList(array))
. - Primitive arrays: Use manual iteration or streams.
- Custom logic: Use streams (e.g., filtering elements while converting).