Append all element of other Collection to ArrayList example

import java.util.ArrayList;
import java.util.List;

/*
 * Here we will learn how to append elements from a Collection to ArrayList.
 */
public class AppendAllElementOfCollection {

	public static void main(String args[]) {
		List<Integer> list = new ArrayList<Integer>();

		/*
		 * add() method appends the specified element to the end of given list.
		 */
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(4);

		List<Integer> listToAppend = new ArrayList<Integer>();

		/*
		 * This is the second collection whose elements needs to be added in
		 * first collection
		 */
		listToAppend.add(5);
		listToAppend.add(6);
		listToAppend.add(7);
		listToAppend.add(8);

		System.out.println("Elements in Arraylist");
		/*
		 * As ArrayList implements Iterable, ArrayList can be used in extended
		 * For Loop
		 */
		for (int i : list)
			System.out.println(i);

		/**
		 * ArrayList have a Overloaded method(addAll(Collection<? extends E> c))
		 * which appends all of the elements in the specified collection to the
		 * end of given list, in the order elements are returned by the
		 * specified collection's iterator. The behavior of this operation is
		 * undefined if the specified collection is modified while the operation
		 * is in progress.
		 */
		list.addAll(listToAppend);

		System.out
				.println("nElements in ArrayList after appending all elements from Collection");

		for (int i : list)
			System.out.println(i);

	}
}

 

By | 2012-09-18T13:36:51+00:00 September 18th, 2012|Code Base|0 Comments

About the Author:

Leave A Comment