Pages

Vector in java

What is Vector?
  • The vector class extends AbstractList and implements the List interface.
  • Like ArrayList, it is a resizable array or growable array of objects
  • Duplicates are allowed
  • It also maintains insertion order
  • Supports heterogeneous objects(different type of objects)
  • null insertion allowed (v.add(null))  //where v ---> vector
  • Vector implements serializable, cloneable, Iterable, List  and RandomAccess

Constructors::

1) Vector v=new Vector(); # creates an empty vector object with default initial capacity 10.Once vector reaches its max. capacity then a New vector object created with 
//New capacity= currentcapacity * 2 ;  (double of default capacity 10)

2) Vector v=new Vector(int initialcapacity);  # create an empty Vector with specified initial capacity.
ex: Vector v=new Vector(10);    # will create a vector of initial capacity of 10

3) Vector v=new Vector(Collection c);  # create an equivalent Vector object for the given collection.

4) Vector object= new vector(int initialcapacity, capacityIncrement)
ex: Vector v=new Vector(5,9);

##sample demo program ###
import java.util.Enumeration;
import java.util.Vector;

public class VectorDemo {
public static void main(String[] args) {
Vector v = new Vector<>();
System.out.println("default inital capacity ::" + v.capacity());
v.addElement(10);
v.addElement(10);
v.addElement("string type");
v.addElement(1.2f);
v.addElement(1);
v.addElement(null);
System.out.println("vectorList elements ::" + v);
System.out.println("vector elements class ::" + v.getClass());
System.out.println("Retrive element from vector :" + v.get(2));

// Display vector elements
Enumeration e = v.elements();
while (e.hasMoreElements()) {
System.out.println("displaying vector element " + e.nextElement());
}
}
}
output:
Vector program in java
Vector program in java

Please comment below to feedback or ask questions.

No comments:

Post a Comment

Please comment below to feedback or ask questions.