THINK FIRST·CODE LATER

← All labs

A stack two ways: is-a or has-a?

Problem

A stack only allows push, pop and peek at its top. Build it twice, on top of ArrayList<String>:

  • InheritedStack extends ArrayList<String> — adds push, pop, peek (inheritance, "is-a");
  • ComposedStack — has a private ArrayList<String> field and offers push, pop, peek, isEmpty, size, toString (composition, "has-a").

TwoStacks reads words until the end of the input and pushes each word on both stacks. Then it shows the weakness of the first design: inherited.add(0, "INTRUDER") and inherited.remove(inherited.size() - 2) compile and break the stack discipline, while the same calls on the composed stack do not even compile (leave that line as a comment). Finally both stacks are emptied. For the input

red green blue

the program prints

Inherited [red, green, blue], top blue
Composed stack: [red, green, blue], top blue
After add(0, ...) and remove(...): [INTRUDER, red, blue]
Popping the inherited stack: blue red INTRUDER
Popping the composed stack: blue green red

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.

l14-8-data-1.txt

red green blue
What your program must print for l14-8-data-1.txt
Inherited [red, green, blue], top blue
Composed stack: [red, green, blue], top blue
After add(0, ...) and remove(...): [INTRUDER, red, blue]
Popping the inherited stack: blue red INTRUDER
Popping the composed stack: blue green red

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

Windows PowerShell does not understand <:

Get-Content l14-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.