Vectors in Java

Vectors in Java

Vectors are growable arrays that need to be initialized before it is used. Vector is a Java class and to use it, import the java.util package like this,

The size is to be mentioned in Java Arrays before being used, and once set, it cannot be changed, unlike Vectors. Therefore, Vectors implement a dynamic array.

The following are the methods provided by Vectors,


Let us learn about the methods in Vectors,

void addElements(Object elements)Add an element to the vector.
void insertElementAt(Object element, int index)Insert an element at a specified index.
boolean removeElement(Object element)Remove the first occurrence of the element.
void removeElementAt(int index)Remove an element from a given index.
void removeAllElements()Remove all the elements. Empties the vector and the size is set to 0.
Object firstElement()Returns the first element.
Object lastElement()Returns the last element.
Object ElementAt(int index)Returns the element at a specified index.
int indexOf(Object element)Returns the index of the first occurrence of the element
int lastIndexOf(Object element)Returns the index of the last occurrence of the element
boolean contains(Object a[])Returns true if the vector has elements.
boolean isEmpty()True is returned if the vector is empty.
Object clone()Returns the clone of the vector.
int capacity()Returns the capacity of the vector.
int size()Returns the count of elements in the vector
void trimToSize()Sets capacity to the elements it currently holds
void setsize(int s)Set a new size for the vector.

Now let us see an example to understand the working of Vectors in Java,


The following is the output,


Vectors in Java

In this lesson, we learned about Vectors and the usage of its methods.

Multidimensional Arrays in Java
Strings in Java
Studyopedia Editorial Staff
Studyopedia Editorial Staff
[email protected]

We work to create free tutorials for all.

No Comments

Post A Comment