Adding one ArrayList to another ArrayList using addAll() method

In this article, we will add one ArrayList to another ArrayList contents using addAll method of Collection interface

 

Adding one ArrayList contents to another ArrayList using addAll method :

Method signature:

boolean addAll(Collection c);
  • This method is used to add one ArrayList contents to another ArrayList contents
  • Returns true, if this list changed as a result of the call

AddOneArrayListToAnotherArrayList.java

package in.bench.resources.java.collections;

import java.util.ArrayList;

public class AddOneArrayListToAnotherArrayList {

	public static void main(String[] args) {

		// 1: creating ArrayList object of type String
		ArrayList<String> al1 = new ArrayList<String>();

		// adding elements to ArrayList object
		al1.add("Sundar Pichai");
		al1.add("Satya Nadella");  
		al1.add("Shiv Nadar");  
		al1.add("Shantanu Narayen");

		// Iterating using enhanced for-loop
		System.out.println("Iterating original ArrayList\n");
		for(String str : al1) {
			System.out.println(str);
		}


		// 2: creating ArrayList object of type String
		ArrayList<String> al2 = new ArrayList<String>();

		// adding elements to ArrayList object
		al2.add("Narayan Murthy"); 
		al2.add("Nandan Nilekeni");
		al2.add("Shibulal SD");

		boolean boolAddAll = al1.addAll(al2);
		System.out.println("\n\nWhether invoking AL changed : "
				+ boolAddAll);

		// Iterating using enhanced for-loop
		System.out.println("\n\nIterating after"
				+ " addAll operation\n");
		for(String str : al1) {
			System.out.println(str);
		}
	}
}

Output:

Iterating original ArrayList

Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen


Whether invoking AL changed : true


Iterating after addAll operation

Sundar Pichai
Satya Nadella
Shiv Nadar
Shantanu Narayen
Narayan Murthy
Nandan Nilekeni
Shibulal SD

Explanation:

From above example, ArrayList

  • allows duplicate elements
  • null object is allowed
  • while iterating insertion-order is maintained
  • insertion-order is maintained, even after addAll operation

 

References:

 

Happy Coding !!
Happy Learning !!

How to reverse ArrayList contents
Comparing two ArrayList objects using containsAll() method