Java Vector addAll() Method
In Java programming,Vector is a dynamic array that can automatically grow and shrink as needed.Vector The class provides many methods to operate on its elements, among which the addAll(Collection c) method is a very practical method used to add all elements of a collection to the Vector it.
Method Definition
addAll(Collection c) The definition of the method is as follows:
public boolean addAll(Collection extends E> c)
- Parameters:
cis a collection containing the elements to add to theVectorelements in . - Return Value: If
Vectoris changed because of calling this method, returnstrue; otherwise it returnsfalse.
Method Functionality
addAll(Collection c) The function of the method is to add all elements in the specified collection c to the end of the Vector . If the collection c is empty, then the Vector will not change in any way.
Example
Here is a simple example demonstrating how to use the addAll(Collection c) method in the component:
Example
import
java.util.Vector
;
import
java.util.ArrayList
;
import
java.util.Collection
;
public
class
VectorAddAllExample
{
public
static
void
main
(
String
[
]
args
)
{
// Create a Vector
Vector
<
String
vector
=
new
Vector
<>
(
);
// Create an ArrayList
Collection
<
String
collection
=
new
ArrayList
<>
(
);
collection.
add
(
"Apple"
)
;
collection.
add
(
"Banana"
)
;
collection.
add
(
"Cherry"
)
;
// Use the addAll method to add the elements in the ArrayList to the Vector
vector.
addAll
(
collection
)
;
// Output the elements in the Vector
System
.
out
.
println
(
"Vector elements: "
vector
)
;
}
}
Code explanation
- Create a Vector: First, we created a
Vectorobjectvector. - Create a Collection: Then, we created an
ArrayListobjectcollection, and added three string elements to it. - Use the addAll method: By calling
vector.addAll(collection), wecollectionto the end of thevectorit. - Output result: Finally, we print out the
vectorelements in the, and the result will show["Apple", "Banana", "Cherry"].
Notes
- Collection Types:
addAll(Collection c)The method accepts any object that implements theCollectioninterface as a parameter, for exampleArrayList,HashSet, etc. - Element Order: If the collection
cis ordered (such asArrayList), then the elements added to theVectorwill maintain the same order. - Empty Collection: If the collection
cis empty,addAll(Collection c)the method will not have any effect onVectorand returnsfalse.
Java Vector