Enumeration:
- Enumeration interface implemented in java 1.2 version.So Enumeration is legacy interface.
- Enumeration uses elements() method.
- Enumeration can traverse in forward direction only.
- Enumeration having methods like hasMoreElement(),nextElement().
Program:
package com.instanceofjavaforus;
import java.util.Enumeration;
import java.util.Vector;
public class EnumerationDemo {
public static void main(String[] args) {
Vector vector=new Vector();
vector.add("indhu");
vector.add("sindhu");
vector.add("swathi");
vector.add("swathi");
vector.add(null);
vector.add(null);
Enumeration en = vector.elements();
while(en.hasMoreElements()){
System.out.println(en.nextElement());
}
}
}
Output:
indhu
sindhu
swathi
swathi
null
null
Iterator:
- Iterator is implemented on all Java collection classes.
- Iterator uses iterator() method.
- Iterator can traverse in forward direction only.
- Iterator having methods like hasNext(), next(), remove().
Program:
package com.instanceofjavaforus;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;
public class IteratorDemo{
public static void main(String[] args) {
TreeMap treeMap=new TreeMap();
treeMap.put("g", "indhu");
treeMap.put("d", "sindhu");
treeMap.put("3", "swathi");
treeMap.put("d", "sindhu");
if(!treeMap.isEmpty()){
Iterator it=treeMap.entrySet().iterator();
while(it.hasNext()){
Map.Entry obj=(Entry) it.next();
System.out.println(obj.getValue());
}
}
}
}
Output:
swathi
sindhu
indhu
ListIterator:
- ListIterator is implemented only for List type classes
- ListIterator uses listIterator() method.
- ListIterator can traverse in forward and backward directions.
- ListIterator having methods like
- hasNext()
- next()
- previous()
- hasPrevious()
- remove()
- nextIndex()
- previousIndex().
Program:
package com.instanceofjavaforus;
import java.util.ArrayList;
import java.util.ListIterator;
public class ListIteratorDemo{
public static void main(String[] args) {
ArrayList arrayList=new ArrayList();
arrayList.add("indhu");
arrayList.add("sindhu");
arrayList.add("saidesh");
arrayList.add(null);
arrayList.add(null);
ListIterator it=arrayList.listIterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
Output:
indhu
sindhu
saidesh
null
null
No comments