Generic Maximum with a Type Bound
Problem
Write one method that finds the biggest item of a list, for any type that can be compared (numbers and words). The first line is the kind: int (compare as numbers) or word (compare in alphabetical order). The second line has the items separated by spaces. Print the biggest item.
Constraints
- 1 <= items <= 100
- words are lowercase
Examples
Input
int 3 9 -2 7
Output
9
Input
word pear apple zebra
Output
zebra
Solutions
A bounded type parameter lets one method work for all comparable types and still be checked at compile time. The method only needs to know that two items can be compared, not what they are.
/*
* Problem : Run the commands.
* Input : Command lines.
* Output : The biggest item.
* Approach: One generic method
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: One method for every type. "T extends Comparable<T>" says: T has a compareTo method, so two items can be compared.
static <T extends Comparable<T>> T maxOf(java.util.List<T> items) {
T best = items.get(0);
for (T item : items) {
if (item.compareTo(best) > 0) {
best = item;
}
}
return best;
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
String[] values = lines[1].split(" ");
// Step 2: The same method works for a list of Integer and for a list of String.
if (lines[0].equals("int")) {
java.util.List<Integer> numbers = new java.util.ArrayList<Integer>();
for (String value : values) {
numbers.add(Integer.parseInt(value));
}
return new String[] {String.valueOf(maxOf(numbers))};
}
return new String[] {maxOf(java.util.Arrays.asList(values))};
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
java.util.List<String> all = new java.util.ArrayList<>();
while (scanner.hasNextLine()) {
String line = scanner.nextLine().trim();
if (!line.isEmpty()) {
all.add(line);
}
}
String[] lines = all.toArray(new String[0]);
System.out.println(String.join("\n", solve(lines)));
}
}
Hints (2)
- What does extends Comparable promise?
- Why is one method better than two copies?