Java addAll(int index, Collection C) Vector 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.whereas addAll(int index,Collection c) method will insert all the element of the collection from the position mentioned as index.

Signature

public boolean addAll(int index,Collection c)

Inserts all of the elements in the specified collection into this vector, starting at the specified position and will throw java.lang.NullPointerException when the specified collection is null and java.lang.IndexOutOfBoundsException when the index is out of range.

Example

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

import java.util.Vector;

public class AddAllIndexMethodVectorExample 
{
    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);
         }
                
         //lets add vector2 element at index 1 of vector1
         vector1.addAll(1,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 l1 before adding**
String 1
String 2
String 3
String 4
**Elements of l1 after adding**
String 1
String 2
Element 1
Element 2
Element 3
Element 4
String 3
String 4

Leave a Reply

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