THINK FIRST·CODE LATER

← All labs

The equals/hashCode contract

Problem

Write two seat classes with fields row (String) and number (int):

  • BrokenSeat overrides equals only;
  • Seat overrides equals and hashCode (from the same fields, e.g. Objects.hash(row, number)) and toString → A1.

HashContract.main reads booking requests row number name. Every request is added to a HashSet<BrokenSeat>. With Seat, a HashSet<Seat> plus a HashMap<Seat, String> refuse double bookings (A1 refused for Mei: already booked by Lina). At the end print the number of requests and the size of each set.

For the input

A 1 Lina
B 2 Omar
A 1 Mei
A 2 Ana
B 2 Bo

the program prints

A1 booked by Lina
B2 booked by Omar
A1 refused for Mei: already booked by Lina
A2 booked by Ana
B2 refused for Bo: already booked by Omar
Requests: 5
Set of Seat (equals + hashCode): 3 seats
Set of BrokenSeat (equals only): 5 seats
equals says A1 = A1: true
Same hash for equal Seats: true

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.

d14-4-data-1.txt

A 1 Lina
B 2 Omar
A 1 Mei
A 2 Ana
B 2 Bo
What your program must print for d14-4-data-1.txt
A1 booked by Lina
B2 booked by Omar
A1 refused for Mei: already booked by Lina
A2 booked by Ana
B2 refused for Bo: already booked by Omar
Requests: 5
Set of Seat (equals + hashCode): 3 seats
Set of BrokenSeat (equals only): 5 seats
equals says A1 = A1: true
Same hash for equal Seats: true

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 < d14-4-data-1.txt

Windows PowerShell does not understand <:

Get-Content d14-4-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.