Java Vector addAll() Method
In Java programming,Vectoris a dynamic array that can automatically grow and shrink as needed.VectorThe class provides many methods to operate on its elements, among whichaddAll(Collection c)method is a very practical method for adding all elements from a collection toVectorin.
Method Definition
addAll(Collection c)The method definition is as follows:
public boolean addAll(Collection<? extends E> c)
- Parameters:
cis a collection containing the elements to be added toVectorthe elements in it. - Return Value: If
Vectorbecause of calling this method, it has changed, then returnstrue; otherwise returnsfalse。
Method Function
addAll(Collection c)The function of the method is to, for the specified collection,cadd all elements in it toVectorthe end of it. If the collectioncis empty, thenVectorwill not change at all.
Example
The following is a simple example showing how to use theaddAll(Collection c)method:
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 elements from ArrayList to Vector
vector.addAll(collection);
// Output the elements in Vector
System.out.println("Vector elements: " + 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 elements from ArrayList to Vector
vector.addAll(collection);
// Output the elements in Vector
System.out.println("Vector elements: " + vector);
}
}
Code Explanation
- Create Vector: First, we created a
Vectorobjectvector。 - Create Collection: Then, we created a
ArrayListobjectcollection, and added three string elements to it. - Use the addAll Method: By calling
vector.addAll(collection), wecollectionadd all elements in it tovectorin. - Output Result: Finally, we print out
vectorthe elements in it, the result will show["Apple", "Banana", "Cherry"]。
Notes
- Collection Type:
addAll(Collection c)The method accepts any object that implements theCollectioninterface as a parameter, such asArrayList、HashSetetc. - Element Order: If the collection
cis ordered (such asArrayList), then added toVectorthe elements in it will maintain the same order. - Empty Collection: If the collection
cis empty,addAll(Collection c)the method will notVectorhave any effect on, and returnsfalse。
Java Vector