Java Vector addAll(int index, Collection c) Method
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 extends E> c)
Parameter Description
- index: The starting position (index) at which to insert elements. The index starts at 0.
- c: The collection to insert; its element type must be compatible with
Vector's element type.
Return Value
- If both the
Vectoris changed because of calling this method, returnstrue; otherwise it returnsfalse.
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
- First, we created a
Vectorand added three elements:"Apple","Banana"and"Cherry". - Next, we created an
ArrayListand added two elements:"Date"and"Elderberry". - Then, we called the
addAll(1, list)method to insert all elements in theArrayListintoVectorat index1. - 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
- Index Out of Bounds: If the specified
indexexceeds the range ofVector(i.e.,index < 0orindex > size()), it throwsIndexOutOfBoundsExceptionexception. - Empty Collection: If the passed-in collection
cis empty (i.e.,null), it throwsNullPointerExceptionexception. - Performance Issues: Because
Vectoris 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