How to Append All Elements of One ArrayList to Another in Java


In this example we will show how to append all elements of one ArrayList to another in Java.

Source Code

package com.beginner.examples;

import java.util.ArrayList;

public class AppendElementsToArrayList {

	public static void main(String[] args) {
		
		//create an ArrayList1 object.
		ArrayList arrayList1 = new ArrayList();
		
		//Add elements to Arraylist
		arrayList1.add("H");
	    	arrayList1.add("e");
	    	arrayList1.add("l");
	    	arrayList1.add("l");
	    	arrayList1.add("o");
	    
	    	//create another ArrayList2 object.
	    	ArrayList arrayList2 = new ArrayList();
	    	arrayList2.add("W");
	    	arrayList2.add("o");
	    	arrayList2.add("r");
	    	arrayList2.add("l");
	    	arrayList2.add("d");
	    
	    	//append all elements of ArrayList1 to ArrayList2.
	    	arrayList1.addAll(arrayList2);
	    
	    	for(int i=0; i<arrayList1.size(); i++) {
	        	System.out.print(arrayList1.get(i));
	    	}

	}

}

Output:

HelloWorld

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments