Generics (concept)

Computer Science · Java

Question 1 of 10

0

    In HashSet<Character> letters, the element type is:

    Stuck? Read the explanation

    Unlocks at a streak of 5 correct answers in a row.

    Print a free worksheet (PDF)

    Embed this practice on your site or class page

    Paste this HTML into your page. Students practise right there; it is free and needs no account.

    Generics (concept) explained

    Generics let a class or method work with a type that the caller chooses, such as String or Integer, and the compiler checks that type. Before generics, collections held Object values and needed casts, which could fail at run time.

    A generic class declares a type parameter in angle brackets, such as class Box. T is replaced by a real type where the class is used, as in Box. A generic method declares its own type parameter before the return type. Type parameters stand only for reference types, so you write List rather than List. Java converts between int and Integer automatically, which is called autoboxing. Generics are erased at run time, so List and List are the same class in the running program. The type checks happen at compile time.

    class Box<T> {
        private T item;
    
        void set(T item) {
            this.item = item;
        }
    
        T get() {
            return item;
        }
    }
    
    Box<String> b = new Box<>();
    b.set("hello");
    System.out.println(b.get().length());
    

    Worked example

    Trace the code above.

    1. Box makes T stand for String, so set accepts only a String.
    2. b.set("hello") stores the value.
    3. b.get() returns a String, so the compiler knows that .length() is available.
    4. "hello" has 5 characters, so 5 is printed. A call such as b.set(42) would be rejected at compile time.

    What you will practise

    103 multiple-choice questions (Easy, Medium, Hard). Each answer is followed by an explanation.

    Example questions

    • Generics:
    • ArrayList<String>:
    • A generic method uses:
    • Generics prevent:
    • The diamond operator is:
    • In class Box<T>, the letter T is:
    • Which of these can be used as a type argument, as in List<...>?
    • The wildcard in List<?> means:

    …and 95 more.