Generic Pair Class
Problem
Write a generic class Pair that holds two values of the same type and has swap(), which gives a new Pair with the values exchanged, and a text form (first, second). Every input line is: type a b, where type is int or str. For int, the values are numbers (007 becomes 7); for str, they stay text. Print the swapped pair for each line, for example (5, 3).
Constraints
- 1 <= lines <= 10^4
- |numbers| <= 10^9
Examples
Input
int 3 5 str a b
Output
(5, 3) (b, a)
Input
int 007 5
Output
(5, 7)
Solutions
A generic class is written once and works for many types, and the compiler (Java, TypeScript) checks that both values have the same type. Immutable objects like this one return a new object instead of changing themselves.
/*
* Problem : Process lines.
* Input : Several lines.
* Output : One pair per line.
* Approach: Generic class.
* Time : O(n)
* Space : O(n)
* Java : 8 or newer.
*/
import java.util.Scanner;
public class Main {
// Step 1: Pair<T> works for any type T. The type is chosen when the pair is created.
static class Pair<T> {
private final T first;
private final T second;
Pair(T first, T second) {
this.first = first;
this.second = second;
}
// Step 2: swap() does not change this pair. It returns a new pair.
Pair<T> swap() {
return new Pair<>(second, first);
}
@Override
public String toString() {
return "(" + first + ", " + second + ")";
}
}
// This method solves the task. It receives the input and returns the answer.
static String[] solve(String[] lines) {
String[] output = new String[lines.length];
for (int i = 0; i < lines.length; i++) {
String[] part = lines[i].split(" ");
// Step 3: Pair<Long> and Pair<String> use the same class code.
if (part[0].equals("int")) {
output[i] = new Pair<Long>(Long.parseLong(part[1]), Long.parseLong(part[2])).swap().toString();
} else {
output[i] = new Pair<String>(part[1], part[2]).swap().toString();
}
}
return output;
}
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 (1)
- Why does swap() return a new pair?