Sei sulla pagina 1di 7

STUDENT LESSON

AB27 Java Lists and Iterators

ICT 2006, www.ict.org, All Rights Reserved

Java Curriculum for AP Computer Science, Student Lesson AB27

STUDENT LESSON AB27 Java Lists and Iterators


INTRODUCTION: ArrayList, part of the Java List Collection, was introduced in Lesson A15, ArrayList. . As demonstrated throughout this curriculum, lists are very useful. This lesson will cover the List Interface and the two different implementations of Lists: ArrayList and LinkedList. Iterators will be covered as well as the different methods of storage used by the two implementations. The key topics for this lesson are: A. The List Interface B. The ArrayList Class C. The LinkedList Class D. Traversing a List using Iterator or ListIterator Objects E. LinkedList vs ArrayList VOCABULARY: ITERATOR LINKEDLIST A. The List Interface The AP subset of the Java List interface is shown below: interface java.util.List AP subset
int size() boolean add(Object x) Object get(int index) Object set(int index, Object x) Iterator iterator() ListIterator listIterator()

LIST ITERATOR TRAVERSE

DISCUSSION:

In order to implement a List, you must use the methods listed in the interface. Java provides two implementations for a List: ArrayList and LinkedList. Like ArrayList and other collection classes, LinkedList stores references to objects.
List < ClassName > classList = new LinkedList < ClassName >(); classList.add(new ClassName(APCS)); ... ClassName favoriteClass = classList.get(1)

This creates classList as a List implemented as a LinkedList. Declaring classList as a List restricts the methods for classList
ICT 2006, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

Java Curriculum for AP Computer Science, Student Lesson AB27

to those in the List interface. Instantiating classList as a LinkedList means it is stored as a LinkedList. B. The ArrayList Class 1. The ArrayList class, java.util.ArrayList, provides the following methods in addition to the List methods:
void add(int index, Object x) Object remove(int index)

2. The basics of using the ArrayList class were explained in Lesson A15, ArrayList. C. The LinkedList Class 1. The LinkedList class is based on the linked list data structure, just as the ArrayList class is based on the array data structure. An array is a random access data structure of contiguous elements. Any element in an array can be accessed directly using an index. In a linked list, the elements are connected by links and are not necessarily contiguous. In a linked list, the elements cannot be accessed directly; the elements must be accessed sequentially, following the links until the desired element is reached. A good analogy for an array is the viewing of a DVD (digital video disc). Any scene in a movie on a DVD can be accessed directly using the DVD scene selection menu to 'jump' to the scene. By contrast, playing a videocassette tape is an example of a linked list. To reach a scene with a videocassette recorder/player (VCR), the tape must be advanced through all of the previous scenes. Some high-end VCRs have a feature that automatically goes back and marks the beginning and end of each commercial of a recorded program. Then, when playing the tape with the commercial advance feature turned on the VCR fast-forwards over the ads to skip them. To the user, it appears that the VCR is accessing the marked positions directly. However, the VCR internally sequences through the taped commercials to reach the marked positions. This is similar to what happens in a linked list when accessing an element by an index. 2. The LinkedList class, java.util.LinkedList, provides the following methods in addition to the List methods:
void addFirst( Object x) void addLast(Object x) Object getFirst() Object getLast() Object removeFirst() Object removeLast()

3. To declare a reference variable for a LinkedList, do the following.


// myLinkedList is a reference to an LinkedList
ICT 2006, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

Java Curriculum for AP Computer Science, Student Lesson AB27

// object. LinkedList <ClassName> myLinkedList = new LinkedList <ClassName> ();

4. An object can be declared as a List and created as a LinkedList or ArrayList. In that case, only the methods of List are available to the object. The advantage is that either implementation can be chosen without having to change any of the code that uses the object.
if (implementationChoice.equals(LinkedList)) { List <String> list = new LinkedList <String>(); } if (implementationChoice.equals(ArrayList)) { List <String> list = new ArrayList <String>(); } list.add(John); list.add(George); for(String temp : list){ System.out.println(temp); }

Notice that the for each loop can be used here. A for each loop can be used in any collection that implements Iterable. D. Traversing a List using Iterator or ListIterator Objects 1. A traversal of a list is an operation that visits all the elements of the list in sequence and performs some operation. 2. An iterator is an object associated with the list. When an iterator is created, it points to a specific element in the list, usually the first. The iterator provides methods to check whether there are more elements to be visited, to obtain the next element, and to remove the current element. This makes it easy to traverse a list. Using an iterator helps prevent OBOBs ('Off-By-One-Bugs': attempts to access an element beyond the length of the list) because the iterator knows how big the list is. 3. In Java, iterators are defined by the library interface, java.util.Iterator. 4. Iterator defines three basic methods:
Object next() // Returns the next element in the iteration boolean hasNext() // Returns true if the iteration has more elements void remove() // Removes the last element returned by next from the list

5. A list traversal would be implemented using an iterator as follows.


LinkedList <String> list = new LinkedList <String>();
ICT 2006, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

Java Curriculum for AP Computer Science, Student Lesson AB27

// Add values to the list ... Iterator <String> iter = list.iterator(); while (iter.hasNext()){ System.out.println(iter.next()); }

Note that the list provides the iterator. 6. A limitation of the Iterator interface is that an iterator always starts at the beginning of the list and can only move forward. 7. A more comprehensive ListIterator object is returned by Lists listIterator method. ListIterator extends Iterator. A ListIterator can start at any specified position in the list and can proceed forward or backward. For example:
ListIterator <String> listIter = list.listIterator(list.size()); while (listIter.hasPrevious()){ String value = listIter.previous(); // process value ... }

8. Some useful ListIterator methods are summarized below:


Object next() // Returns the next element in the iteration. void add(Object x) // Inserts the argument into the list being iterated over. void set(Object x) // Replaces the last element returned by next by the argument.

9. The following two examples illustrate one of the advantages of iterators. Example 1:
LinkedList <String> list = new LinkedList <String>(); // Add values to the list list.add("John"); list.add("Ann"); list.add("Betsy"); list.add("Nancy"); for(int i = 0; i < list.size(); i++){ String value = list.get(i); System.out.println(value); if(value.equals("Ann")) list.remove(i); }

ICT 2006, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

Java Curriculum for AP Computer Science, Student Lesson AB27

Run Output:
John Ann Nancy

Example 2:
LinkedList <String> list2 = new LinkedList <String>(); // Add values to the list list2.add("John"); list2.add("Ann"); list2.add("Betsy"); list2.add("Nancy"); Iterator <String> listIter = list2.iterator(); while (listIter.hasNext()){ String value = listIter.next(); System.out.println(value); if(value.equals("Ann")) listIter.remove(); }

Run Output:
John Ann Betsy Nancy

In Example 1, the index is external to the list, so after removing Ann, i is incremented but the elements of the list have changed positions and Betsy is skipped. In Example 2, the iterator keeps track of the positions of the elements after Ann is removed and Betsy is not skipped. E. LinkedList vs ArrayList An important aspect of good programming is to choose the best data structure to solve a particular problem. Here are some advantages and disadvantages of using one versus the other - LinkedList vs ArrayList: Operation Searching LinkedList Best performance is O(N) because the list must be searched sequentially even if it is ordered. Performance is O(1) no matter how big the list is. At most, two elements are affected (see Lesson AB30). Performance is O(N). ArrayList Best performance is O(log N) if the list is ordered because a binary search can be used. Performance is O(N) because many elements of the list may have to be moved. Performance is O(1).

Insertion/deletion

Accessing by index

ICT 2006, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

Java Curriculum for AP Computer Science, Student Lesson AB27

When designing a program to build a telephone directory, for example, ArrayList might be a better choice than LinkedList. The directory would not change often, so insertion/deletion would not be a major concern. However, fast searching would be important. On the other hand, LinkedList might be better for a print spooler program. Print jobs will frequently be inserted (when a new print request is received) and deleted (when the print job is sent to the physical printer). The list could even be prioritized so that small print jobs would be inserted near the front of the list. However, searching through the list for a particular print job would not be a common occurrence. SUMMARY/ REVIEW: Java provides two implementations of the List interface: ArrayList and LinkedList. Both implementations allow a program to use the standard methods of List as well as to take advantage of methods specific to each implementation. Iterators are useful for traversing lists. Each implementation of List has advantages that make it well suited for different tasks. Lab Assignment AB27.1, MergeList Lab Assignment AB27.1, Data File, file20.txt

ASSIGNMENT:

ICT 2006, www.ict.org, All Rights Reserved Use permitted only by licensees in accordance with license terms (http://www.ict.org/javalicense.pdf)

Potrebbero piacerti anche