Java Reference
In-Depth Information
remove() fails with an exception if the queue is empty while poll() returns
null .
10.6.2 Using java.util.Iterator
We mentioned above that the Iterator interface is preferred over the old
Enumeration interface. The original object containers from Java 1.0 days used
the Enumeration interface to provide a way to loop over the elements in the
container. All the old container classes were retro-fitted with the Java 1.2 release
to support the Iterator interface as well. The new container classes added
in JDK 1.2 along with the Collections Framework support only the Iterator
interface. As mentioned, Iterator is preferable to Enumeration because
Iterator allows the caller to remove elements from the underlying collection
during an iteration without corrupting the Iterator .
The syntax for iterating over the elements in a Vector is as follows:
Vector vec = new Vector;
// Populate it...Then later, iterate over its elements
Iterator it = vec.iterator ();
while (it.hasNext ()) {
Object o = it.next ();
}
Here, since we haven't been specific about what kinds of objects were put into the
Vector ,weshow retrieving the elements as plain java.lang.Object types.
Next
we
illustrate
another
popular
iteration
style,
this
time
using
an
ArrayList ,which is preferred over Vector in a thread-safe situation:
ArrayList a - list = new ArrayList ();
...
for (Iterator it = a - list.iterator (); it.hasNext ();) {
Object o = it.next ();
}
Again, we retrieve plain java.lang.Object types from the Iterator . All
these container objects, Vector , ArrayList , and all the others, accept input
of any kind of object. They can do this because the add() method receives
java.lang.Object as the parameter type, and since java.lang.Object
is the superclass of all other object types, any kind of object can be added.
But the containers don't know what kinds of objects are being stored in them
(see, however, the generics feature of J2SE in the next section). Therefore, when
retrieving an object from one of the containers, it can only be returned as a
java.lang.Object type. In most cases, you need to cast the Object received
into the specific object type you desire. You, as the programmer, should know
what kind of objects you store into a container, so you can do the cast correctly.
Search WWH ::




Custom Search