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

Java Vector addAll() Method

Java Vector addAll() Method

Java Vector Java Vector

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 c)

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

  1. Create a Vector: First, we created a Vector object vector.
  2. Create a Collection: Then, we created an ArrayList object collection, and added three string elements to it.
  3. Use the addAll method: By calling vector.addAll(collection), we collection to the end of the vector it.
  4. Output result: Finally, we print out the vector elements in the, and the result will show ["Apple", "Banana", "Cherry"].

Notes

  1. Collection Types:addAll(Collection c) The method accepts any object that implements the Collection interface as a parameter, for example ArrayList, HashSet , etc.
  2. Element Order: If the collection c is ordered (such as ArrayList), then the elements added to the Vector will maintain the same order.
  3. Empty Collection: If the collection c is empty,addAll(Collection c) the method will not have any effect on Vector and returns false.

Java Vector Java Vector