Methods of Vector

The Vector class also provides the resizable-array implementations of the List interface (similar to the ArrayList class). Some of the Vector methods are:

Add Elements to Vector

  1. add(element) - adds an element to vectors
  2. add(index, element) - adds an element to the specified position
  3. addAll(vector) - adds all elements of a vector to another vector

For example,


\begin{lstlisting}
import java.util.Vector;
\par
class Main {
public static voi...
...mammals);
System.out.println(''New Vector: '' + animals);
}
}
\end{lstlisting}

Output


\begin{lstlisting}
Vector: [Dog, Horse, Cat]
New Vector: [Crocodile, Dog, Horse, Cat]
\end{lstlisting}

Access Vector Elements

  1. get(index) - returns an element specified by the index
  2. iterator() - returns an iterator object to sequentially access vector elements

For example,


\begin{lstlisting}
import java.util.Iterator;
import java.util.Vector;
\par
clas...
...m.out.print(iterate.next());
System.out.print('', '');
}
}
}
\end{lstlisting}

Output


\begin{lstlisting}
Element at index 2: Cat
Vector: Dog, Horse, Cat,
\end{lstlisting}

Remove Vector Elements

  1. remove(index) - removes an element from specified position
  2. removeAll() - removes all the elements
  3. clear() - removes all elements. It is more efficient than removeAll()

For example,


\begin{lstlisting}
import java.util.Vector;
\par
class Main {
public static voi...
... System.out.println(''Vector after clear(): '' + animals);
}
}
\end{lstlisting}

Output


\begin{lstlisting}
Initial Vector: [Dog, Horse, Cat]
Removed Element: Horse
New Vector: [Dog, Cat]
Vector after clear(): []
\end{lstlisting}