Generic Pair
Completed
Write class Pair<A, B> with first(), second(), swap() (returns Pair<B, A>) and toString (a, b). Read a name and an age, make a pair, print it and its swap.
Input
One line: name age.
Output
Two lines.
Example
Input
Ada 36
Output
(Ada, 36) (36, Ada)
Editor
Java
Hints
A class can have several type parameters.
Solution explanation
swap() shows that generic types can be rearranged in return types.
Show solution
import java.util.Scanner;
class Pair<A, B> {
private final A a;
private final B b;
Pair(A a, B b) {
this.a = a;
this.b = b;
}
A first() { return a; }
B second() { return b; }
Pair<B, A> swap() {
return new Pair<B, A>(b, a);
}
@Override
public String toString() {
return "(" + a + ", " + b + ")";
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Pair<String, Integer> p = new Pair<String, Integer>(sc.next(), sc.nextInt());
System.out.println(p);
System.out.println(p.swap());
}
}