Task 3 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

9.1 Generic classes — writing a generic class

Lesson

Declaring and using the type parameter

Write the parameter after the class name: class Box<T>. Inside the class, use T as if it were a real type — for fields, for parameters, and for return types. When you create an object you supply the actual type: new Box<String>("hi"), and every T becomes String for that object.


Worked example

class Box<T> {
    private T item;                        // field of type T
    public T get() { return item; }        // returns a T
    public void set(T item) { this.item = item; }   // takes a T
}

Box<String> b = new Box<String>("first");
b.set("second");   // only Strings accepted
System.out.println(b.get());   // second

T is not a real class — it is a stand-in that the compiler replaces with whatever type you chose.


▶ Try it: run this — set replaces the item, get returns it with the right type.



Where do you declare the type parameter?


Inside a generic class, T can be used as...


Type exactly what this program prints.

class Box<T> {
    private T item;
    public Box(T i){ item=i; }
    public T get(){ return item; }
    public void set(T i){ item=i; }
}
public class Main { public static void main(String[] a){
    Box<Integer> b = new Box<Integer>(1);
    b.set(9);
    System.out.println(b.get());
}}

For Box<Integer> b, calling b.set("hi") gives...


True or false?