vector in java
- This is a predefined class and can be used to store the data of different type (float, int, character, string).
- It is defined inside the java.util package.
- It is same as traditional arrays of Java, except that, it grows as per requirement.
- Elements of vector can be accessed by their index number which starts from zero.
- Vectors are in Synchronized form.
- Vectors implement a dynamic array which means it can grow or shrink as per our requirement.
- It is commonly used when there is no idea about the number of elements in an array.
- There are three different ways to create vector.
1. Vector vec = new Vector();
- It creates an empty Vector which is of capacity 10.
- The default or initial capacity of vector will be 10.
2. Vector vec = new Vector(5);
- This creates a Vector of initial capacity of 5.
3. Vector vec = new Vector(5,10);
- Here 5 is the initial capacity whereas 10 is the capacity of 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#
*/
0 Comments