Generics — Writing Your Own in Java
Beyond using built-in generic collections, a custom class or method can declare its own type parameter, conventionally a single capital letter like T, E, or K, in angle brackets right after its name — class Box<T> { T contents; } defines a Box that can hold any single type, with the actual type filled in at the point of use, like Box<String> or Box<Integer>. A generic method works the same way but scopes its type parameter to just that one method rather than the whole class, declared in angle brackets right before the return type.
Bounded type parameters restrict what a type parameter can actually be — T extends Number means T must be Number or one of its subclasses, which then makes Number's own methods callable on values of type T inside the generic code, something an unbounded T wouldn't allow at all, since an unbounded T could be absolutely anything.
Declaring a generic class
class Box<T> { T contents; } defines a class parameterized by a type filled in later, at the point of use.
Using a generic class
Box<String> and Box<Integer> are two different, fully type-safe specializations of the same general Box definition.
Declaring a generic method
A type parameter in angle brackets right before the return type scopes it to just that one method.
Bounded type parameters
T extends Number restricts T to Number or its subclasses, making Number's own methods callable on T inside the generic code.
Naming conventions
T for a general type, E for a collection element, K and V for a map's key and value, all just conventions the compiler doesn't enforce.
public class GenericBoxDemo { static class Box<T> { T contents; Box(T contents) { this.contents = contents; } } public static void main(String[] args) { Box<String> stringBox = new Box<>("hello"); Box<Integer> intBox = new Box<>(42); System.out.println("String box: " + stringBox.contents); System.out.println("Int box: " + intBox.contents); }}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Java yourself — building beats watching.