Java Reference
In-Depth Information
If, however, you cast a returned Object to a type that it does not represent (say,
you cast an Integer to a String ), then you will be greeted with a runtime
ClassCastException .
We next illustrate the ability of the Iterator to remove elements. First we
make a list of integers from 0 to 19 and then remove all the odd integers:
// Build an ArrayList and populate it with integers from
//0to19.
ArrayList al = new ArrayList ();
for (int i=0; i < 20; i++) al.add (i);
// Iterate through the ArrayList, removing all the odd
// integers.
int count = 0;
for (Iterator it = al.iterator (); it.hasNext ();) {
count++;
it.next ();
if (count%2 == 0) it.remove ();
}
// Print out the remaining elements with another Iterator.
for (Iterator it = al.iterator (); it.hasNext ();) {
System.out.println ("element is " + it.next ());
}
The first loop simply loads the integers from 0 to 19 into the ArrayList . The
next loop uses an iterator to retrieve each element and remove the ones when
count%2 is zero. The final loop uses another iterator to print out the contents
of the modified list. Note that we used the Iterator.remove() method, not
ArrayList.remove() . Attempting to remove an element directly from the
ArrayList generates a runtime ConcurrentModificationException .
Note also that we used the autoboxing feature (see Chapter 3) to add primitive
int types in the first loop (autoboxed to Integer type) without having to
explicitly convert them to Integer wrapper types.
10.7 Generics in J2SE 5.0
We said above that the object containers expect to hold java.lang.Object
types and that the returned Object types must be cast into the desired type.
J2SE 5.0 includes the very significant addition of “generics” in which the object
containers can actually “know” what object type they should contain [1,2]. Then,
an attempt to insert an object of the wrong type into them results in a compile-
time error rather than a runtime ClassCastException . Generics are a large
and important addition to Java, and we only scratch the surface of how to use
Search WWH ::




Custom Search