Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Java Vector addAll(int index, Collection c) Method

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 into the Vector at the specified position.

The syntax of this method is as follows:



public boolean addAll(int index, Collection c)

Parameter Description

Return Value


Method Functionality

addAll(int index, Collection c) The main function of the method is to insert all elements in the collection c into the specified position of the Vector in order index. After insertion, the original Vector in the, starting from index will shift backward to make room for the new elements.


Example

Here is a simple example demonstrating how to use addAll(int index, Collection c) method in the component:

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 of the ArrayList at index 1 of the Vector

        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 Analysis

  1. First, we created a Vector and added three elements:"Apple", "Banana" and "Cherry".
  2. Next, we created an ArrayList and added two elements:"Date" and "Elderberry".
  3. Then, we called the addAll(1, list) method to insert all elements in the ArrayList into Vector at index 1 .
  4. Finally, we output the contents of the Vector ; you can see that the new elements are inserted successfully and the original elements shift backward.

Notes

  1. Index Out of Bounds: If the specified index exceeds the range of Vector (i.e., index < 0 or index > size()), it throws IndexOutOfBoundsException exception.
  2. Empty Collection: If the passed-in collection c is empty (i.e., null), it throws NullPointerException exception.
  3. Performance Issues: Because Vector is implemented based on arrays; insertion operations may cause array reallocation and element copying, so performance issues should be noted when processing large amounts of data.

Java Vector Java Vector