Java Reference
In-Depth Information
No other pairs can be removed, so we lose.
Write a program that simulates this game. It should generate 40 random two-digit integers and place them in an
instance of java.util.ArrayList , using an instance of ListIterator . Then, using this iterator, scan the list and
remove matching pairs of values. After each pair is removed, use an iterator to display the values remaining in the list.
5.
One statistical operation that is sometimes performed on a set of data values is to remove values that are far from
the average. Write a program that reads real values from a text file, one per line. Store the data values as Double
objects in an instance of the class java.util.ArrayList . Then
Use an iterator to compute the average and standard deviation of the values. Display these results.
Use a second iterator to remove any value that is more than two standard deviations away from the
average.
Use a for-each loop to display the remaining values and compute the new average. Display the new
average.
If the data values are x 1 , x 2 , ..., x n , their average
μ
is their sum divided by n , and their standard deviation is
n
¦
1
---
2
σ
=
(
x i
-
μ
)
i
=
1
6.
Consider the following situation. You create a list, and then you add 10 items to it. You get an iterator to the list
and call next twice to advance it. You remove the first five items from the list, using the list's remove method. You
then call the iterator's remove method, expecting to remove the item last returned by the method next . However,
this entry has already been removed from the list. Changing the state of the list while using the iterator, as you
have done here, may result in unpredictable behavior of the iterator.
Modify the interface Iterator so that the methods will throw the exception StateChangedException if the
state of the list is changed after the iterator was created but before the method is called. Modify the implementation
of LinkedListWithIterator that Project 1 describes to accommodate the changes to Iterator .
7.
Revise the class ArrayListWithIterator outlined in Segment 15.24 so that it extends the class AList , as
discussed in Chapter 13.
8.
Repeat Projects 7 and 8 of Chapter 12, adding an iterator to the ADT recipe.
A NSWERS TO S ELF -T EST Q UESTIONS
1.
The output is
true
Rachel
2.
nameIterator.next();
nameIterator.next();
System.out.println(nameIterator.next());
3.
nameIterator.next(); // skip first entry; list has > 1 entry
while (nameIterator.hasNext())
{
System.out.println(nameIterator.next()); // display even-numbered entry
if (nameIterator.hasNext())
nameIterator.next();
// skip odd-numbered entry
} // end while
4.
while (nameIterator.hasNext())
{
nameIterator.next();
nameIterator.remove();
} // end while
 
Search WWH ::




Custom Search