Generic Box
Completed
Write class Box<T> with set, get and isEmpty. Store a String and an Integer in two boxes and print their contents and the Integer doubled.
Input
Line 1: a word. Line 2: an integer.
Output
Three lines.
Example
Input
hello 21
Output
hello 21 42
Editor
Java
Hints
T is a type parameter - a placeholder for the real type.
Solution explanation
Generics give type safety without casts: number.get() is already an Integer.
Show solution
import java.util.Scanner;
class Box<T> {
private T value;
void set(T value) {
this.value = value;
}
T get() {
return value;
}
boolean isEmpty() {
return value == null;
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
Box<String> word = new Box<String>();
Box<Integer> number = new Box<Integer>();
word.set(sc.next());
number.set(sc.nextInt());
System.out.println(word.get());
System.out.println(number.get());
System.out.println(number.get() * 2);
}
}