Java Reference
In-Depth Information
With 5.0, the collection object “knows” what type it holds, so it returns that type
instead of the Object type.
In the pre-5.0 days, iterating through a list of strings and printing each out
required code like this:
List list - of - strings = new ArrayList ();
...
for (Iterator it = list - of - strings.iterator (); it.hasNext
();) {
String s = (String) it.next ();
Sytem.out.println (s);
}
But when list - of - strings is a List < String > type, this simplifies to:
for (Iterator it = list - of - strings.iterator (); it.hasNext
();) {
String s = it.next ();
Sytem.out.println (s);
}
No more explicit cast! With autoboxing and unboxing, we can insert and retrieve
primitive types without explicitly using the wrapper objects:
List<Integer> list - of - ints = new ArrayList<Integer> ();
...
for (Iterator it = list - of - ints.iterator (); it.hasNext
();) {
int i = it.next ();
...
}
We should warn you of a nuisance with the J2SE 5.0 compiler. The use of these
special type-safe containers removes a significant source of errors. For backward
compatibility, all the old containers are still available. So any pre-5.0 code con-
tinues to work exactly the same in 5.0 and beyond. However, because the old
container types are potentially unsafe, the 5.0 javac compiler now issues warn-
ings about possible unsafe usage whenever it encounters one of the old container
types. These are just warnings and can be ignored if you are sure that the code is
safe. The best way to get rid of the warnings is to switch to the use of the generic
types where appropriate.
Of course, sometimes the old non-type-safe containers are needed, such as
when you really want to insert a mix of object types. In this case, you can just
ignore the warnings. Alternatively, the metadata system discussed in Chapters 1
and 4 provides an @SuppressWarnings annotation to explicitly suppress such
warnings.
Search WWH ::




Custom Search