C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Then: We invoke the Collections.addAll method. This method receives two arguments.
Collections.addAllArgument 1: The first argument to Collections.addAll is the ArrayList we want to add elements to.
Argument 2: This is the String array reference. These elements are added to the end of the ArrayList.
Java program that initializes ArrayList with String array
import java.util.ArrayList;
import java.util.Collections;
public class Program {
public static void main(String[] args) {
// Initialize ArrayList with contents of string array.
String[] array = {"bird", "fish"};
ArrayList<String> animals = new ArrayList<>();
Collections.addAll(animals, array);
// The ArrayList now contains all strings.
System.out.println(animals);
}
}
Output
[bird, fish]
Copy: We use the ArrayList's copy constructor to add all the elements from one ArrayList to the new one.
Java program that uses ArrayList copy constructor
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
// Create an ArrayList with two elements.
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(10);
list1.add(20);
// Initialize an ArrayList from another ArrayList of the same type.
ArrayList<Integer> list2 = new ArrayList<>(list1);
list2.add(30);
// The collections are separate.
System.out.println(list1);
System.out.println(list2);
}
}
Output
[10, 20]
[10, 20, 30]
Java program that uses addAll, many arguments
import java.util.ArrayList;
import java.util.Collections;
public class Program {
public static void main(String[] args) {
// Initialize many values in one statement.
ArrayList<String> colors = new ArrayList<>();
Collections.addAll(colors, "blue", "red", "green", "yellow");
// Print colors.
System.out.println(colors);
}
}
Output
[blue, red, green, yellow]
Capacity: We use a capacity on our ArrayList. This reduces resizes when many elements are added—space is reserved.
Java program that uses ints, for-loop, initializes ArrayList
import java.util.ArrayList;
public class Program {
public static void main(String[] args) {
// Initialize with capacity.
ArrayList<Integer> values = new ArrayList<>(10);
// Initialize an ArrayList of Integers in a loop.
for (int i = 0; i < 10; i++) {
values.add(i);
}
// Print ArrayList and its size.
System.out.println(values);
System.out.println(values.size());
}
}
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
10