Java Vector addAll() Method

Java Vector Java Vector

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: IfVectorbecause 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);
    }
}

Code Explanation

  1. Create Vector: First, we created aVectorobjectvector。
  2. Create Collection: Then, we created aArrayListobjectcollection, and added three string elements to it.
  3. Use the addAll Method: By callingvector.addAll(collection), wecollectionadd all elements in it tovectorin.
  4. Output Result: Finally, we print outvectorthe elements in it, the result will show["Apple", "Banana", "Cherry"]。

Notes

  1. Collection Type:addAll(Collection c)The method accepts any object that implements theCollectioninterface as a parameter, such asArrayList、HashSetetc.
  2. Element Order: If the collectioncis ordered (such asArrayList), then added toVectorthe elements in it will maintain the same order.
  3. Empty Collection: If the collectioncis empty,addAll(Collection c)the method will notVectorhave any effect on, and returnsfalse。

Java Vector Java Vector

Other Extensions