THINK FIRST·CODE LATER

← All labs

addAll, removeAll, retainAll in your own array list

Problem

Java's collections offer three "bulk" operations; write them yourself. In ListSetOps, write a generic class MyArrayList<E> on a growing array (add, get, contains, size, toString, and a copy constructor) with

public boolean addAll(MyArrayList<E> other)     // adds every element of other
public boolean removeAll(MyArrayList<E> other)  // removes the elements that are also in other
public boolean retainAll(MyArrayList<E> other)  // keeps only the elements that are also in other

Each returns true if the list changed. removeAll and retainAll must work in one pass, without a second array: move the elements to keep towards the front.

main reads two lines of words, A and B (a line - is an empty list), and applies each operation to a copy of A. For the input

Tom George Peter Jean Jane
Tom George Michael Michelle Daniel

the program prints

A = [Tom, George, Peter, Jean, Jane], B = [Tom, George, Michael, Michelle, Daniel]
addAll changed the list: true -> [Tom, George, Peter, Jean, Jane, Tom, George, Michael, Michelle, Daniel]
removeAll changed the list: true -> [Peter, Jean, Jane]
retainAll changed the list: true -> [Tom, George]
A is untouched: [Tom, George, Peter, Jean, Jane] (5 elements)

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.

d10-8-data-1.txt

Tom George Peter Jean Jane
Tom George Michael Michelle Daniel
What your program must print for d10-8-data-1.txt
A = [Tom, George, Peter, Jean, Jane], B = [Tom, George, Michael, Michelle, Daniel]
addAll changed the list: true -> [Tom, George, Peter, Jean, Jane, Tom, George, Michael, Michelle, Daniel]
removeAll changed the list: true -> [Peter, Jean, Jane]
retainAll changed the list: true -> [Tom, George]
A is untouched: [Tom, George, Peter, Jean, Jane] (5 elements)

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 < d10-8-data-1.txt

Windows PowerShell does not understand <:

Get-Content d10-8-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.