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

Java Vector add() Method

Java Vector add(Object o) Method

Java Vector Java Vector

add(Object o) The method is used to add the specified element to the Vector end of the

The syntax of this method is as follows:


public boolean add(Object o)

Parameters

Return Value

Example

Here is a simple example demonstrating how to use the add(Object o) method to add elements to the Vector :

Example

import

java.util.Vector

;

public

class

VectorExample

{

   

public

static

void

main

(

String

[

]

args

)

{

       

// Create a Vector object

        Vector

<

String

vector

=

new

Vector

<>

(

)

;

       

// Use the add method to add elements to the Vector

        vector.

add

(

"Apple"

)

;

        vector.

add

(

"Banana"

)

;

        vector.

add

(

"Cherry"

)

;

       

// Output the elements in the Vector

       

System

.

out

.

println

(

"Elements in the Vector: "

vector

)

;

   

}

}

Output result

Vector 中的元素: [Apple, Banana, Cherry]

Method details

1. Adding an Element

add(Object o) The method adds the specified element to the Vector end of the. If the Vector current capacity is insufficient to hold the new element, theVector automatically expands its capacity.

2. Thread safety

Vector is thread-safe, which means multiple threads can operate on Vector simultaneously without causing data inconsistency.add(Object o) The method is also thread-safe, so it can be used safely in a multithreaded environment.

3. Return Value

add(Object o) The method always returns true, indicating that the element has been successfully added to the Vector . This is because Vector can always expand its capacity to accommodate new elements, so the add operation will not fail.


Notes

Type Safety: Starting from Java 5,Vector supports generics, so it is recommended when using Vector to specify the element type to avoid type conversion errors. For example:


Vector vector = new Vector<>();

Performance considerations: Because Vector is thread-safe, so in a single-threaded environment, using ArrayList may be more efficient.ArrayList is not thread-safe, but performs better in a single-threaded environment.

automatic resizing:Vector automatically expands its capacity when adding elements, but frequent expansion operations may affect performance. Therefore, when the number of elements is known, performance can be optimized by specifying the initial capacity.

Java Vector Java Vector