Defenitions:
Set: an unordered array of elements or objects
Collection: an ordered set
1.Vectors already implement the Collection interface, but you can define your own Collection.
2.ArrayLists and Vectors, both support Iterators
Enumeration
An enumeration is an object that generates elements one at a time, used for passing through a collection, usually of unknown size.
The traversing of elements can only be done once per creation.
Enumeration’s have two options:
nextElement() which returns the next object in the collection
hasMoreElements() which returns true, until the last object has been returned by nextElement()
Code Example:
import java.util.Vector;
import java.util.Enumeration;
public class EnumerationTester {
public static void main(String args[]) {
Enumeration days;
Vector dayNames = new Vector();
dayNames.add(“Sun”);
dayNames.add(“Mon”);
dayNames.add(“Tues”);
dayNames.add(“Wednes”);
dayNames.add(“Thurs”);
dayNames.add(“Fri”);
dayNames.add(“Satur”};
days = dayNames.elements();
while (days.hasMoreElements())
System.out.println(days.nextElement()); } }
Enumerations do not allow for the modification of the collection, which is being traversed, thus the Iterators are used if this is required.
Iterators have 3 options:
hasNext() returns true if there is another element in the collection
next() which returns the next object
remove() which removes the last object taken using next()
No comments:
Post a Comment