Java Reference
In-Depth Information
Continued from previous page
// this version of the code is correct
while (itr.hasNext()) {
String current = itr.next();
if (current.length() > longest.length()) {
longest = current;
}
}
As the compiler processes the for-each loop, it essentially converts the loop into
the following code:
Iterator<String> i = list.iterator();
while (i.hasNext()) {
String word = i.next();
System.out.println(word + " " + word.length());
}
There's a more advanced version of Iterator called ListIterator that works
only on lists. A ListIterator provides operations like adding elements, setting ele-
ment values, and reversing iteration from back to front. Because it is more complex,
we won't discuss ListIterator in detail in this topic. You can read more about it
online in Sun's Java API and Java Tutorial pages.
In summary, the following table compares the major benefits of ArrayList and
LinkedList :
Collection
Strengths
• Random access: any element can be accessed quickly
• Adding and removing at the end of the list is fast
ArrayList
• Adding and removing at either the beginning or end of the list is fast
• Adding and removing during a sequential access with an iterator is fast
• Unlike with arrays, there is no need to expand when full
• Can be more easily used as a queue than arrays can
LinkedList
Abstract Data Types (ADTs)
It's no accident that the LinkedList collection provides the same methods as the
ArrayList . They both implement the same kind of collection: a list. At a high level,
the most important thing isn't the way the list is implemented internally, but the oper-
ations we can perform on it. This set of operations is an example of an abstract data
type, or ADT.
 
Search WWH ::




Custom Search