Vector Class in Java

 

Vector is a concrete class in Collection Framework.

Vector is dynamic representation of array and is synchronized

Since vector is synchronized so it will better choice for thread safe operation.

synchronization- It is a process through which an object can be locked for a given thread and other thread cannot use that object when it is locked.
 

Example:
—MyVector.java—

 

 OUTPUT:

Vector-Output

vector_methods

Methods in Vector Class

Collections Framework in Java has a Vector class. This Vector class has very useful methods, lets see some of the methods in Vector Class with examples.

Example-1:
Vector accepts object. like btn are accepted as object.

 

Example-2:
Auto boxing converts primitives converted into objects.

 

Example-3:
In this example we make Vector to accept only Strings we can say we make it type safe. Now if we pass integer then the program will give compile time error.

OUTPUT:

type_safe
 

Example-4:
Downcasting Example

OUTPUT:

downcasting
 

Example-5:
Difference between type add and addElement method

 

Example-6:
Accessing vector using foreach loop

OUTPUT:

foreach
 

OUTPUT: -->

-->

Example-9:

//enumeration is used with vector
//enumeration is a kind of pointer which access all the elements or traverse all the elements.

OUTPUT:
empid=7841
name=abhi1
empid=7441
name=agg1
 

 
Example-11:

OUTPUT:
two
one
apple
three
four

//by the output it is observed that set method accept two parameters
// first is the location where in the vector we have to insert the
//new object second parameter is the object and also set() return the
//object that is over written by the incoming object
 

Example-12:

OUTPUT:

methods in vector

 

Example-13:
Difference between setElementAt and insertElementAt

 

OUTPUT:

vector_methods