Chapter 7 Iterators

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

LinkedList: add()

-A LinkedList supports insertion of elements either at the end of the list or at a specified index. -If an index is not provided, as in authorList.add("Martin");, the add() method adds the element at the end of the list. If an index is specified, as in authorList.add(0, "Rowling");, the element is inserted at the specified index, with the list element previously located at the specified index appearing after the inserted element.

Iterator Issues

-First: You may not want to process all of the elements in the collection. The for-each loop starts at the beginning of the collection and doesn't stop until it reaches the end of the collection (you could force the loop to break, but that isn't clean or ever advised). -Second: If you want to remove an element from the collection, you need to chose the explicit iterator. The for-each loop doesn't provide explicit access to the iterator. Other issues: -Don't assume the iterator delivers the elements in any particular order unless documentation guarantees it. -The structure of the collection should not be changed while iterator is being used. -Most iterators in the Java API are fail-fast, meaning they throw a ConcurrentModificationException if the collection is modified while

LinkedList: get() and set()

-The get() method returns the element at the specified index. -To access the specified list element, the get() method will start at the first list element and then traverse the list element by element until the specified index is reached. -Ex: playerName.get(3) starts at the element located at index 0, moves to the element at index 1, then moves to index 2, and finally moves to index 3 returning that element. -The set() method replaces the element at the specified location with a new element.

next() method vs hasNext()

-The next() method returns the next element in the list and moves the ListIterator to the next location. -The hasNext() method returns true if there is a next element, and false otherwise. -A good practice is to always call hasNext() before calling next() to ensure a list element exists.

The LinkedList

-an ADT implemented as a generic class that supports different types of elements. -can be declared and created as LinkedList<T> linkedList = new LinkedList<T>(); where T represents the LinkedList's type, such as Integer or String. -import java.util.LinkedList; enables use of a LinkedList within a program.

Iterator

-an object that allows the user to acquire and use each element in a collection one at a time. -It works in conjunction with a collection but is a separate object. -An iterator is a mechanism for helping implement a collection. -The Java API uses the concpet of iterators by nearly all of the collections in the class library. -You have used the concept often when reading from a text file using the Scanner class.

LinkedList: ListIterator

-an object that points to a location in a List and provides methods to access an element and advance the ListIterator to the next position in the list. -LinkedList's listIterator() method returns a ListIterator object for traversing a list. -The statement import java.util.ListIterator; enables use of a ListIterator in a program.

The List interface

-defines a Collection of ordered elements, i.e., a sequence -supports methods for adding, modifying, and removing elements.

1) You can modify a collection while an iterator is active. True False 2) Since a for-each loop is cleaner, it should be the go to iterator at all times. True False

1) False It cause a ConcurrentModificationException if the collection is modified while the iterator is active. 2) False Although for-each loops may be easier to understand, they can not remove an element or stop at a specified element.

1)The Iterable interface creates an Iterator that can be iterated through. True False 2) All iterators provide a remove function to remove an element from a collection. True False 3) Which of the following is NOT a method of the iterator interface remove hasNext isNext next

1) True The method iterator of the Iterable interface does return an iterator of the collection. 2) False The iterator interface provides the function, but it is an optional operation and not all iterators implement it. 3) isNext This is not a method of the interface

1. An iterator is in essence a loop to step through (iterate through) a collection True False 2. The hasNextLine method of the Scanner class, moves the pointer to the next line in the text file. True False 3. The String variable line, will contain all of the data from the text file at the end of loop. True False

1. True To iterate (or step) through a collection means to move from one element in the collection to the next until reaching the end of the collection. 2. False It simply verifies that the current line of text has information to read. 3. False At each iteration of the loop, the variable is assigned a new value (data from a line in the text file).

Given the following code that creates and initializes a LinkedList: LinkedList<Double> accelerometerValues = new LinkedList<Double>(); accelerometerValues.add(9.8); accelerometerValues.add(10.2); accelerometerValues.add(15.4); 1. Complete the statement to print the first list element. System.out.println(accelerometerValues. ); 2. Complete the statement to assign currentValue with the element at index 2. currentValue = accelerometerValues. ; 3. Complete the statement to update the element at index 1 to 10.6. accelerometerValues. ; 4. Write a statement to remove the value 9.8 from the list. accelerometerValues. ;

1. get(0) get(0) returns the first element in accelerometerValues. 2. get(2) Assigns currentValue with the value 15.4. 3. set(1, 10.6) Replaces the element at index 1 with 10.6. 4. remove(0) Removes the element located at index 0.

There are two key interfaces in the Java API to work with iterators:

Iterator - used to define an object that can be used as an iterator Iterable - used to define a collection that provides an iterator

LinkedList vs. ArrayList

LinkedList and ArrayList are ADTs implementing the List interface. Although both LinkedList and ArrayList implement a List, a programmer should select the implementation that is appropriate for the intended task. A LinkedList typically provides faster element insertion and removal at the list's ends (and middle if using ListIterator), whereas an ArrayList offers faster positional access with indices. In this material, we use the LinkedList class, but the examples can be modified to use ArrayList.

ListIterator hasNext() and set() example: LinkedList<String> authorsList = new LinkedList<String>(); String authorName; String upperCaseName; ListIterator<String> listIterator; authorsList.add("Gamow"); authorsList.add("Greene"); authorsList.add("Penrose"); listIterator = authorsList.listIterator(); while (listIterator.hasNext()) { authorName = listIterator.next(); upperCaseName = authorName.toUpperCase(); listIterator.set(upperCaseName); } listIterator = authorsList.listIterator(); while (listIterator.hasNext()) { authorName = listIterator.next(); System.out.println(authorName); }

Output: GAMOW GREENE PENROSE ***ListIterator's set() method replaces the last element accessed by the iterator, such as the prior next() call. All strings in the list have been replaced with uppercase versions.

ListIterator Example: LinkedList<String> authorsList = new LinkedList<String>(); String authorName; ListIterator<String> listIterator; authorsList.add("Gamow"); authorsList.add("Greene"); authorsList.add("Penrose"); listIterator = authorsList.listIterator(); while (listIterator.hasNext()) { authorName = listIterator.next(); System.out.println(authorName); }

Output: Gamow Greene Penrose ***listIterator() method returns a ListIterator object for iterating through list elements. -ListIterator's hasNext() method returns true if the list has more elements. Otherwise, returns false. -ListIterator's next() method returns the next element in the list and moves the iterator to the next location.

What is the output? LinkedList<String> authorsList = new LinkedList<String>(); String authorName; int i; authorsList.add("Gamow"); authorsList.add("Greene"); authorsList.add("Penrose"); for (i = 0; i < authorsList.size(); ++i) { authorName = authorsList.get(i); System.out.println(authorName); }

Output: Gamow Greene Penrose **The get() method always traverses the list sequentially from the first element to the desired element.

Example of add(): LinkedList<String> authorsList = new LinkedList<String>(); authorsList.add("Gamow"); authorsList.add("Penrose"); authorsList.add("Hawking"); authorsList.add(1, "Greene");

Output: Gamow Greene Penrose Hawking ***The add() method adds an element, such as a String, to the end of the list. Using the add() method with an index inserts an element at the specified index.

LinkedList: remove() System.out.println(authorsList.get(1)); authorsList.remove(1); System.out.println(authorsList.get(1)); authorList: Gamow Greene Penrose

Output: Greene Penrose ***The remove() method removes the element at the specified position.

Example of get() and set(): System.out.println(authorsList.get(2)); authorsList.set(2, "Sagan"); System.out.println(authorsList.get(2)); authorsList: Gamow Greene Penrose

Output: Penrose Sagan ***The get() method searches through the LinkedList to return the element at the specified index. The set() method replaces the element at the specified position.

ListIterator: set()

The ListIterator's set() method replaces the last element accessed by the iterator, e.g., the element returned by the prior next() call.

The Iterable interface Method: Iterator<E> iterator()

has only one method, called iterator, that returns an Iterator object. Notice the angle brackets and letter E, the collection is using generics. When you instantiate the collection, you specify the Data (element) type, which is used to define the elements in the iterator. In Java, a LinkedList is Iterable, so it provides a method called iterator, which can be used in any class derived from LinkedList. The ArrayList class is also Iterable.

Answer the questions given the following code that creates and initializes a LinkedList and a ListIterator. For every question, assume that the ListIterator is located before the first list element (i.e., the starting position). LinkedList<Integer> numbersList = new LinkedList<Integer>(); ListIterator<Integer> numberIterator; numbersList.add(3); numbersList.add(1); numbersList.add(4); numberIterator = numbersList.listIterator(); 1)What does numberIterator.hasNext() return the first time? 2)What value does numberIterator.hasNext() return after three calls to numberIterator.next(). 3) Given the original list initialization above, what is the value of numVal after executing the following statements? numberIterator.next(); numVal = numberIterator.next(); 4)Complete the code to replace the next list element with newDigit. numberIterator.next(); // Necessary! numberIterator. ___________ ;

1)true A call to numberIterator.next() would return an element, i.e., 3. Thus, hasNext() returns true. 2)false The iterator is positioned after the last element, so hasNext() returns false. 3)1 The second call to next() returns the second element of the list, which is 1. 4) set(newDigit) The next() method returns the next list element and moves the ListIterator. The set() method replaces the element returned by the previous call to next().

LinkedList<String> wordsFromFile = new LinkedList<String>(); wordsFromFile.add("The"); wordsFromFile.add("fowl"); wordsFromFile.add("is"); wordsFromFile.add("the"); wordsFromFile.add("term"); 1. At what index does the following statement insert the word "end"? Enter a number. wordsFromFile.add("end"); 2. Given the original list initialization above, how many elements does wordsFromFile contain after the following statement? Enter a number. wordsFromFile.add(4, "big"); 3. Write a statement to insert the word "not" between the elements "is" and "the". wordsFromFile.add( );

1. 5 If an index is not specified, the add() method adds to the end of the list. 2. 6 The add() method increases the list's size by one because add() does not replace elements. 3. 3, "not" "not" is inserted at index 3. The string "the", which was previously located at that index, is located at index 4 after the insertion.


Ensembles d'études connexes

Business Ethics Final Exam Study Guide

View Set

Chapter 1 Review Questions PSYCH 21A

View Set

multiplication rule for dependent events

View Set