Java: A generic box

Write your first generic class and use it with two different types.

What to build

A generic Box used to hold a number and a label.

Requirements

  • Write class Box<T> holding one value that may be absent, with get(), set(T value), isEmpty() and toString() giving Box(VALUE) or Box(empty).
  • Read a label and a number. Create a Box<String> with the label and an empty Box<Integer>; print both; set the integer box to the number times 2; print it again.

Input

Line 1: a label. Line 2: a whole number.

Output

Three lines.

Constraints

The number fits in an int and doubling it does not overflow.

Example

Input:

apples
21

Output:

Box(apples)
Box(empty)
Box(42)

Why it works

One generic class works for both types, and Box<Integer> returns an Integer that can be used in arithmetic without a cast.

Examples

Example 1 · Input
apples
21
Expected output
Box(apples)
Box(empty)
Box(42)
Example 2 · Input
two words
-5
Expected output
Box(two words)
Box(empty)
Box(-10)

Hints

Hint 1

class Box<T> with a private T value, get, set and isEmpty (value == null).

Hint 2

Use Box<Integer> for the count and Box<String> for the label.

Solution

Show one correct solution (try it yourself first)
import java.util.Scanner;

public class Main {
    static class Box<T> {
        private T value;

        Box(T value) { this.value = value; }
        T get() { return value; }
        void set(T value) { this.value = value; }
        boolean isEmpty() { return value == null; }

        @Override
        public String toString() {
            return "Box(" + (isEmpty() ? "empty" : value) + ")";
        }
    }

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        String label = in.nextLine();
        int n = Integer.parseInt(in.nextLine().trim());
        Box<String> text = new Box<>(label);
        Box<Integer> number = new Box<>(null);
        System.out.println(text);
        System.out.println(number);
        number.set(n * 2);
        System.out.println(number);
    }
}

Lesson: Generics →