Generics and Classes

Intermediate Algorithms and Data Structures English
Also available: Deutsch
Created by Best · 16.08.2026 at 09:13 UTC

Generics parameterize types: Box stores T. The compiler checks assignments and removes casts. At runtime, due to type erasure, often only the raw form exists.

Advantage: fewer ClassCastExceptions, clearer APIs. Limitation: no new T[], no instanceof T with type parameter.

Example: List accepts add("a"), but not add(Integer).

Wildcard Read Write
? extends T as T usually forbidden
? super T as Object insert T
## Where used

Typed repositories, event bus handlers, collection APIs. Generics shift class errors to compile time and are a prerequisite for readable library boundaries in large codebases.

Depth

A type parameter describes a family of classes with the same structure but different element types. The compiler checks insertion and removal consistently, which eliminates many runtime conversions.

Box<Integer> is not a subtype of Box<Number>. This invariance prevents, for example, writing a Double into a box that is actually an integer box via a supposedly Box<Number>.

Static members belong to the class and not to a specific type argument instantiation. Therefore, they cannot directly use the type parameter of the instance class. Methods can instead declare their own type parameters.

Difficulty levels

  1. Use a class type parameter in fields and methods.
  2. Justify invariance based on an unsafe write access.
  3. Distinguish between class and method type parameters.

Pitfalls

A single letter is not a concrete runtime type. Additionally, an unchecked cast only removes the compiler check, not the possibility of a later type error.

University approvals: 0
Tasks
Question 1

What is the main advantage of List over a raw List?

Question 2

Why is Box<Integer> not a subtype of Box<Number>?

Question 3

Complete the generic class Box with set and get.

Hint

The type parameter T can be used like a normal reference type for fields, parameters, and return values.

Starter code is prefilled; replace TODO blocks with your solution.
1 test case will be used for grading
Run checks runtime behavior only. Final correctness is evaluated when you submit.
Card Info
  • Topic: Algorithms and Data Structures
  • Difficulty: Intermediate
  • Completed: 0 users
Creator
Best
Best
BestBuddy