Java Vector addAll(int index, Collection c) Method


Java Vector Java Vector

addAll(int index, Collection c)The method is used to insert all elements in the specified collection intoVectorthe specified position of

The syntax of this method is as follows:

public boolean addAll(int index, Collection<? extends E> c)

Parameter Description

  • index: The starting position (index) for inserting elements. The index starts from 0.
  • c: The collection to be inserted, whose element types must be compatible withVectorthe element types of the Vector.

Return Value

  • IfVectorchanges as a result of calling this method, it returnstrue; otherwise, it returnsfalse。

Method Functionality

addAll(int index, Collection c)The main function of the method is to insert all elements in the collectioncin order into theVectorspecified position ofindex. After insertion, the originalVectorfrom theindexelements starting at that position are shifted backward to make room for the new elements.


Example

The following is a simple example demonstrating how to use theaddAll(int index, Collection c)method:

Example

import java.util.Vector;
import java.util.ArrayList;

public class VectorAddAllExample {
    public static void main(String[] args) {
        // Create a Vector
        Vector<String> vector = new Vector<>();
        vector.add("Apple");
        vector.add("Banana");
        vector.add("Cherry");

        // Create an ArrayList
        ArrayList<String> list = new ArrayList<>();
        list.add("Date");
        list.add("Elderberry");

        // Insert all elements in the ArrayList into the Vector at index 1
        vector.addAll(1, list);

        // Output the contents of the Vector
        System.out.println("Vector after addAll: " + vector);
    }
}

Output Result

Vector after addAll: [Apple, Date, Elderberry, Banana, Cherry]

Code Explanation

  1. First, we created aVectorand added three elements:"Apple"、"Banana"and"Cherry"。
  2. Next, we created anArrayListand added two elements:"Date"and"Elderberry"。
  3. Then, we called theaddAll(1, list)method to insert theArrayListall elements in the collection into theVectorindex of the Vector at1.
  4. Finally, we outputVectorthe contents, and we can see that the new elements were successfully inserted, and the original elements moved backward.

Notes

  1. Index out of bounds: If the specifiedindexexceeds the range of theVector(i.e.index < 0orindex > size()), an exception will be thrownIndexOutOfBoundsExceptionexception.
  2. Empty collection: If the passed-in collectioncis empty (i.e.null), an exception will be thrownNullPointerExceptionexception.
  3. Performance concerns: Since VectorVectoris implemented based on arrays, insert operations may lead to array reallocation and element copying, so performance needs to be considered when handling large amounts of data.

Java Vector Java Vector

Other Extensions