Java Vector addAll(Collection c) Method Example

The addAll(Collection c) method of java.util.Vector class will simply inserts all of the elements in the specified collection to the end of the Vector.

Signature

public boolean addAll(Collection c)

This method appends all the elements of a collection at the end of the vector and will throw “java.lang.NullPointerException” when the specified collection is null.

Example

The following example shows the usage of java.util.Vector.addAll(c) method.

import java.util.Vector;

public class AddAllMethodVectorExample 
{
	public static void main(String args[])
	{
		// Create vector1 object
		Vector vector1 = new Vector();
		
		//adding elements to Vector using add()
		vector1.add("Element1");
		vector1.add("Element2");
		vector1.add("Element3");
		vector1.add("Element4");
		
		// Create vector2 object
		Vector vector2 = new Vector();
		vector2.add("String 1");
                vector2.add("String 2");
                vector2.add("String 3");
                vector2.add("String 4");
		
                //Printing the elements of the Vector1
                System.out.println("**Elements of the Vector1 before adding**");
                for(String val : vector1)
                {
    	                System.out.println(val);
                }
      		
                //adding vector2 to vector1
                vector1.addAll(vector2);
		
                //Printing the elements of the Vector1
		System.out.println("**Elements of the Vector1 after adding**");
		for(String val : vector1)
		{
			System.out.println(val);
		}
	}
}

Output

**Elements of the Vector1 before adding**
Element1
Element2
Element3
Element4
**Elements of the Vector1 after adding**
Element1
Element2
Element3
Element4
String 1
String 2
String 3
String 4

Leave a Reply

Your email address will not be published. Required fields are marked *