MainMenu

Home Java Overview Maven Tutorials

Monday 8 April 2019

Data Structure in JAVA

Data Structure in Java, what is Enumeration, vector etc.?



VIDEO :-



The Enumeration

:- It is an Interface
It is available in Java utility package.
Enumeration is used to process the elements of the collection objects which are introduce in jdk 1.0 for example vector.

There are two types of methods declared by Enumeration :-
hasMoreElements :- It returns Boolean value like True or False
nextElement :- It returns the next object in the enumeration.

Here is the Example for Vector and Enumeration :-


import java.util.Vector;
import java.util.Enumeration;

public class ENUM
{
public static void main(String args[])
{
Enumeration name;
Vector starNames = new Vector(5,3); (here 5 and 3 are initial and incremental capacity)
starNames.add("Julia Robert");
starNames.add("keanu reeves");
starNames.add("Akshay");
starNames.add("Maria");
starNames.add("Keira");
starNames.add("Frida");
starNames.add("Will");
name = starNames.elements(); //It will return Enumeration object
while (name.hasMoreElements())
{
System.out.println(name.nextElement());
}
}
}


Output :-

Julia Robert
keanu reeves
Akshay
Maria
Keira
Frida
Will


Vector :- It is a Class
Vector implements a dynamic array.
Implements List Interface & extends AbstractList.
Vector v = new Vector() Creates default vector of capacity 10.
Vector v = new Vector(int size, int incre) defines vectors Initial size & incremental size.

Example of vector class :-

public class Vectortutorial
{
Enumeration enum;
public static void main(String[] args)
{
Vector v = new Vector();
v.add("way2testing");
v.add("chandan");
v.add("Testing Tutorials");
v.add(7);
Iterator itr = v.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
Vector<Integer> vec = new Vector<Integer>();
vec.add(1);
vec.add(2);
vec.add(4);
enum = vec.elements();
while (enum.hasMoreElements())
{
System.out.println(enum.nextElement());
}
}
}

Output :-

way2testing
chandan
Testing Tutorials
1
2
4


Difference between Vector and ArrayList In Java

1). java.util.Vector came along with the first version of java development kit(JDK).
java.util.ArrayList was introduced in java version 1.2 as part of Java collection framework.
2). Vector is synchronized but ArrayList is not or we can say also
"All the methods of vector is synchronized but the methods of ArrayList is not synchronized."
So ArrayList is fast because it is not synchronised & vector is slow because it is synchronized.
3). Vectors doubles(100%) the size of its when its size is increased and ArrayList increases by half(50%) of its size when its size is increased.
4). ArrayList uses Iterator Interface to traverse the elements but A vector can use Iterator interface or Enumeration interface to traverse the elements.

No comments:

Post a Comment