Vector Example program
Java Vector Class
- Java Vector class comes under the java.util package. The vector class implements a growable array of objects. Like an array, it contains the component that can be accessed using an integer index.
- Vector is very useful if we don't know the size of an array in advance or we need one that can change the size over the lifetime of a program.
- Vector implements a dynamic array that means it can grow or shrink as required. It is similar to the ArrayList, but with two differences-
- Vector is synchronized.
- The vector contains many legacy methods that are not the part of a collections framework
Three ways to create vector class object:
1.Vector vec=new Vector()
Method 2:
Syntax:
Syntax:
Vector object= new Vector(int initialCapacity)
Method 3:
Vector object= new vector(int initialcapacity, capacityIncrement)
Example program :
- import java.util.*;
- public class VectorExample1 {
- public static void main(String args[]) {
- //Create an empty vector with initial capacity 4
- Vector<String> vec = new Vector<String>(4);
- //Adding elements to a vector
- vec.add("Tiger");
- vec.add("Lion");
- vec.add("Dog");
- vec.add("Elephant");
- //Check size and capacity
- System.out.println("Size is: "+vec.size());
- System.out.println("Default capacity is: "+vec.capacity());
- //Display Vector elements
- System.out.println("Vector element is: "+vec);
- vec.addElement("Rat");
- vec.addElement("Cat");
- vec.addElement("Deer");
- //Again check size and capacity after two insertions
- System.out.println("Size after addition: "+vec.size());
- System.out.println("Capacity after addition is: "+vec.capacity());
- //Display Vector elements again
- System.out.println("Elements are: "+vec);
- //Checking if Tiger is present or not in this vector
- if(vec.contains("Tiger"))
- {
- System.out.println("Tiger is present at the index " +vec.indexOf("Tiger"));
- }
- else
- {
- System.out.println("Tiger is not present in the list.");
- }
- //Get the first element
- System.out.println("The first animal of the vector is = "+vec.firstElement());
- //Get the last element
- System.out.println("The last animal of the vector is = "+vec.lastElement());
- }
- }
Out put sir
ReplyDeleteSir Java structure' s post chyendii
ReplyDeleteTiger
ReplyDeleteLion
Dog
Elephant
Rat
Cat
Deer
Out put ila vasthe
Naku deer anadhi tiger ki lion ki madyalo ravali ante Emily cheyali sir