TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

<< Back to JAVA

Java Collections.addAll: Add Array to ArrayList

Add arrays to ArrayLists with the Collections.addAll method. See common errors in appending arrays.
Collections.addAll. An array has many elements. These can be added to an ArrayList. With Collections.addAll we can add an array of elements to an ArrayList.ArrayList
Some limitations. With addAll, we must have element types that match. An Integer ArrayList is incompatible with an int array. Often we must use a for-loop to add an array.
First example. This program uses a String array and an ArrayList of Strings. It combines a one-element ArrayList with a String array of three elements.

Collections.addAll: This method receives two arguments: the collection (ArrayList) we are adding to, and the values we are adding.

Java program that uses Collections.addAll import java.util.ArrayList; import java.util.Collections; public class Program { public static void main(String[] args) { String[] values = { "cat", "dog", "bird" }; // Create a one-element ArrayList. ArrayList<String> list = new ArrayList<>(); list.add("elephant"); System.out.println(list); // Add all elements to the ArrayList from an array. Collections.addAll(list, values); // Display our result. System.out.println(list); } } Output [elephant] [elephant, cat, dog, bird]
Integer, int conversion. Here we add an int array to an ArrayList with Integer elements. We use a for-loop, as the array cannot be directly added.

Result: We add all three elements from "sizes" to the ArrayList. We do not need an index value in this loop.

For
Java program that uses Integer ArrayList, int array import java.util.ArrayList; public class Program { public static void main(String[] args) { // An int array. int[] sizes = { 100, 200, 300 }; // Create an Integer ArrayList. ArrayList<Integer> list = new ArrayList<>(); list.add(500); System.out.println(list); // Loop over our array and add each element separately. for (int element : sizes) { list.add(element); } // The final list. System.out.println(list); } } Output [500] [500, 100, 200, 300]
Collections.addAll error. An int array cannot added to an ArrayList of Integers. An int is not the same thing as an Integer—an Integer is an object that contains an int.ArrayList int, Integer

Quote: An object of type Integer contains a single field whose type is int (Java Documentation).

Java program that shows Integer, int error import java.util.ArrayList; import java.util.Collections; public class Program { public static void main(String[] args) { // Has int elements. int[] sizes = { 100, 200, 300 }; // This has Integer elements. ArrayList<Integer> list = new ArrayList<>(); // Cannot add an int array to Integer ArrayList. Collections.addAll(list, sizes); } } Output Exception in thread "main" java.lang.Error: Unresolved compilation problem: The method addAll(Collection<? super T>, T...) in the type Collections is not applicable for the arguments (ArrayList<Integer>, int[]) at Program.main(Program.java:14)
Casting issue. A cast does not help with the problems of Collections.addAll. We cannot cast an array of ints to Integers. Here is the compilation problem.
Java program that shows casting error import java.util.ArrayList; import java.util.Collections; public class Program { public static void main(String[] args) { int[] sizes = { 100, 200, 300 }; ArrayList<Integer> list = new ArrayList<>(); // This cast does not work. Collections.addAll(list, (Integer[]) sizes); } } Output Exception in thread "main" java.lang.Error: Unresolved compilation problem: Cannot cast from int[] to Integer[] at Program.main(Program.java:14)
Benchmark. Does the addAll method have a performance advantage over a for-loop that calls add? I tested this in a benchmark. I measured both constructs.

Version 1: This version of the code uses Collections.addAll to add an array to an ArrayList.

Version 2: Here we use a for-loop and the add() method on the ArrayList. It has 2 nested loops.

Result: I found that using addAll on a short String array was consistently faster.

String Arrays
Java program that benchmarks Collections.addAll and add import java.util.Collections; import java.util.ArrayList; public class Program { public static void main(String[] args) { String[] elements = { "cat", "dog", "fish" }; long t1 = System.currentTimeMillis(); // Version 1: use addAll method. for (int i = 0; i < 10000000; i++) { ArrayList<String> list = new ArrayList<>(); Collections.addAll(list, elements); if (list.size() != 3) { return; } } long t2 = System.currentTimeMillis(); // Version 2: use for-loop and add. for (int i = 0; i < 10000000; i++) { ArrayList<String> list = new ArrayList<>(); for (String element : elements) { list.add(element); } if (list.size() != 3) { return; } } long t3 = System.currentTimeMillis(); // ... Result. System.out.println(t2 - t1); System.out.println(t3 - t2); } } Output 423 ms, Collections.addAll 463 ms, ArrayList add
Some advantages. There are benefits to Collections.addAll: it reduces lines of code and avoids loops. It is probably faster than a for-loop.
However, incompatible arrays (where int does not match Integer) are not supported. Often to add arrays to ArrayLists, a for-loop is needed.
© TheDeveloperBlog.com
The Dev Codes

Related Links:


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf