Java Reference
In-Depth Information
Iterator iterator = errorMsgsMap.values().iterator ();
while (iterator.hasNext()) {
ErrorMsg myErrorMsg = (ErrorMsg ) iterator.next ();
}
Java 1.5 modified the processing associated with the for loop in order to sim-
plify the use of collections. Essentially, if you are examining the contents of a col-
lection, you can use the { for : each } syntax to examine the contents of a
collection in sequential order, without explicitly defining or managing an iterator.
for (ErrorMsg myErrorMsg : errorMsgsVector)
System.out.println ("Error message: " + myErrorMsg );
Read this statement as “for each ErrorMsg myErrorMsg in errorMsgsVector .”
Notice that this statement places the current value (that is, the value pointed to by
the implied Iterator) into the variable myErrorMsg . This syntax also uses Generics to
simplify and clarify the statement.
O RDERING AND C OMPARISON F UNCTIONS
The Collections class contains several static methods that provide useful functions
on collections, such as sorting and searching. These powerful (and polymorphic)
functions demonstrate some of the benefits provided by collections. They are stan-
dard mechanisms available to any developer who needs to manage a group of related
items. Some examples of the collection algorithms provided with Java are as follows.
sort: Organize a list based on the natural order of the objects in the list, or
based on a comparator (a user-defined ordering method). Sort always orders a
list in ascending order.
reverse: The same function as sort() , but the elements are organized in de-
scending order.
fill: Populate a list with copies of the same element. Existing elements in the list
will be overwritten, so this method is very useful when you want to reinitialize
a list.
replaceAll: Replaces all instances of a particular value with another.
copy: Copy elements from a list into another list. The target list must be large
enough to hold all the elements, but if the target list is larger, then the extra el-
ements will not be affected.
swap: Swaps some of the elements in a list.
Search WWH ::




Custom Search