THINK FIRST·CODE LATER

← All labs

Generic tools: which bound does each method need?

Problem

Write GenericTools with four generic methods, giving each the weakest condition on its type parameter that makes it compile:

  • max(E[][] grid) — the largest element of a two-dimensional array;
  • max(ArrayList<E> list) — the largest element of a list;
  • distinct(ArrayList<E> list) — a new list with the first occurrence of each element;
  • sort(ArrayList<E> list) — sorts the list itself (selection sort).

Three of them need <E extends Comparable<E>>; one works with a plain <E>. Which one, and why?

main reads rows cols, a grid of integers, then a line of words. For the input

2 3
4 9 2
7 -1 8
pear apple fig pear kiwi apple fig

the program prints

Largest number in the grid: 9
Distinct words: [pear, apple, fig, kiwi]
Sorted: [apple, fig, kiwi, pear]
Largest word: pear
Largest of a String grid: west

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.

d2-8-data-1.txt

2 3
4 9 2
7 -1 8
pear apple fig pear kiwi apple fig
What your program must print for d2-8-data-1.txt
Largest number in the grid: 9
Distinct words: [pear, apple, fig, kiwi]
Sorted: [apple, fig, kiwi, pear]
Largest word: pear
Largest of a String grid: west

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

Windows PowerShell does not understand <:

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