Java ArrayList addAll Example

These Java examples use the ArrayList addAll method to add or insert ArrayLists. One ArrayList is added to another.
ArrayList addAll. With addAll, we can add an ArrayList at the end of another ArrayList. The elements are copied. The elements must have the same exact type.ArrayList add, insert
With an index argument, we can insert the contents of one ArrayList into another. We can insert at any valid index. This causes existing elements to be shifted to make room.
First example. Let us begin with an ArrayList of String elements. We use the names of pet cats. We add three Strings to the first ArrayList.

Then: We create a second ArrayList with just one element ("Meow"). With System.out.println we display these ArrayLists.

Console

Finally: We invoke addAll to add the second ArrayList at the end of the first ArrayList.

Java program that uses ArrayList addAll import java.util.ArrayList; public class Program { public static void main(String[] args) { // Create ArrayList and add 3 strings to it. ArrayList<String> cats1 = new ArrayList<>(); cats1.add("Max"); cats1.add("Mittens"); cats1.add("Fluffy"); System.out.println(cats1); // Create a second ArrayList. ArrayList<String> cats2 = new ArrayList<>(); cats2.add("Meow"); System.out.println(cats2); // Add first ArrayList to second. cats2.addAll(cats1); System.out.println(cats2); } } Output [Max, Mittens, Fluffy] [Meow] [Meow, Max, Mittens, Fluffy]
Insert at index. Here we insert one ArrayList's elements into another. We use addAll as an "insert all" or "insert range" method.

Tip: We use an ArrayList of Integers. When we pass int values to add, these are converted to Integers.

ArrayList int, Integer

Result: The contents of the first ArrayList are placed in the second ArrayList. The previous elements are shifted.

Java program that inserts elements with addAll import java.util.ArrayList; public class Program { public static void main(String[] args) { // New ArrayList. ArrayList<Integer> ints = new ArrayList<>(); ints.add(1); ints.add(2); System.out.println(ints); // A second ArrayList. ArrayList<Integer> ints2 = new ArrayList<>(); ints2.add(10); ints2.add(20); System.out.println(ints2); // Insert first ArrayList into second ArrayList. ints2.addAll(1, ints); System.out.println(ints2); } } Output [1, 2] [10, 20] [10, 1, 2, 20]
Collections.addAll. This method allows us to directly add an array to an ArrayList. If you are trying to add an array, use Collections.addAll instead of ArrayList addAll.Collections.addAll
Method choice is important. For most Java ArrayList use, I recommend Collections.addAll—this method is great because it handles arrays, unlike ArrayList addAll.Arrays
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
HomeSearch
Home
Dot Net Perls