Vector in java.
Vector in java
- It is a predefined class and used to store the data.
- We can store data of any data type(float,int,character,string).
- It is defined inside the package java.util.
- It is is similar to a traditional Java array, except that it can grow as necessary to accommodate new elements.
- Elements of vector can be accessed using index number and it starts from zero.
- Vectors are Synchronized.
- Vector implements a dynamic array that means it can grow or shrink as required.
- It is mostly used when there is no idea about the numbers of element in array.
- There are three way to create vector.
- 1. Vector vec = new Vector();
- It will creates an empty Vector of capacity 10.
- The default initial capacity of vector is 10.
- 2. Vector vec = new Vector(5);
- It will create a Vector of initial capacity of 5.
- 3. Vector vec = new Vector(5,10);
- Here 5 is the initial capacity and 10 is the capacity increment.
- It means upon insertion of 6th element the size would be 15 (5+10).
- Example
import java.util.Vector;
import java.util.Enumeration;
class Program
{
public static void main(String args[])
{
/*creating variable of enumeration*/
Enumeration courses;
/*creating object of vector*/
Vector courseName = new Vector();
/*adding data into vector*/
courseName.add("C");
courseName.add("C++");
courseName.add("JAVA");
courseName.add("PHP");
courseName.add("ANDROID");
courseName.add("C#");
/*passing vector data into enumeration*/
courses = courseName.elements();
/*Accessing data of enumeration*/
while (courses.hasMoreElements())
{
/*printing data of enumeration*/
System.out.println(courses.nextElement());
}
}
}
/*
Output
C
C++
JAVA
PHP
ANDROID
C#
*/