Enumeration
Enumeration is a legacy interface its works similar to the Iterator it traverse the element.
- Enumeration can only traverse the element which belongs to only legacy collection.
- Vector can traverse the element with iterator as well as enumeration.
Whenever we create synchronized method then that method in multithreading environment sequentially access.
If suppose add method of Arraylist is unsynchronized then in multithreading environment multiple thread access at the same time that method so working will be fast.
But synchronized method they can’t access simultaneously in multithreading environment they are access sequentially.
You can say Synchronize are thread safe but slow but unsynchronized are fast but not thread safe.
Example
package com.collection.programs;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Vector;
public class VectorAndEnumeration {
public static void main(String[] args) {
// TODO Auto-generated method stub
Vector v = new Vector();
System.out.print(" Initially capacity of a Vector:");
System.out.println(v.capacity());
v.add(10);
v.add(6);
v.add(12);
v.add(8);
v.add(13);
v.addElement(1);
v.addElement(5);
v.addElement(2);
v.addElement(0);
v.addElement(7);
System.out.println(v);
System.out.println("After adding element beyond the cpacity");
v.addElement(9);
System.out.println(v);
System.out.print("then cpacity");
System.out.print(v.capacity());
System.out.println();
System.out.println("Created new Vector object and give capacity as 3 and add elements ");
Vector v1 = new Vector(3);
v1.add(6);
v1.addElement(1);
v1.add(12);
System.out.println(v1);
System.out.println("After adding element beyond the cpacity");
v1.addElement(2);
System.out.println(v1);
System.out.print("then cpacity : ");
System.out.print(v1.capacity());
System.out.println();
}
}
Try it »
Example of fetching data from 3 files One by One using SequenceInputStream, Vector and Enumeration.
Example
public class VectorSequenceInputStreamDemo {
public static void main(String[] args) throws IOException {
InputStream input1 = new FileInputStream("/home/codersarts/file2.txt");
InputStream input2 = new FileInputStream("/home/codersarts/file3.txt");
InputStream input3 = new FileInputStream("/home/codersarts/file4.txt");
Vector streams = new Vector<>();
streams.add(input1);
streams.add(input2);
streams.add(input3);
Enumeration enumeration = streams.elements();
SequenceInputStream sequenceInputStream = new SequenceInputStream(enumeration);
int data = sequenceInputStream.read();
while(data != -1){
System.out.print((char)data);
data = sequenceInputStream.read();
}
sequenceInputStream.close();
}
}
Try it »