THINK FIRST·CODE LATER

← All labs

Removing while iterating: Iterator and ListIterator

Problem

Write IteratorLab. Read a limit, then integers into an ArrayList<Integer>.

  1. On a copy, try the wrong way: remove the values greater than the limit inside a for-each loop. Catch ConcurrentModificationException and print which happened (the exception, or — by luck — no exception and the resulting list).
  2. On the original, remove them correctly with Iterator.remove() and print how many were removed.
  3. Copy the result into a LinkedList and walk it with a ListIterator: replace each negative value by 0 (set), and insert value + 1 right after each even non-negative value (add).
  4. With the same iterator, walk backwards (hasPrevious, previous) and print the values.

For the input

10 4 15 8 -3 22 6

the program prints

start: [4, 15, 8, -3, 22, 6]
for-each removal: ConcurrentModificationException
removed 2 values above 10: [4, 8, -3, 6]
after set/add: [4, 5, 8, 9, 0, 6, 7]
backwards: 7 6 0 9 8 5 4

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d4-6-data-1.txt

10 4 15 8 -3 22 6
What your program must print for d4-6-data-1.txt
start: [4, 15, 8, -3, 22, 6]
for-each removal: ConcurrentModificationException
removed 2 values above 10: [4, 8, -3, 6]
after set/add: [4, 5, 8, 9, 0, 6, 7]
backwards: 7 6 0 9 8 5 4

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d4-6-data-1.txt

Windows PowerShell does not understand <:

Get-Content d4-6-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.