Java Generics
Angle Brackets in Java
Type Parameters
Java Programming
Java Syntax

What does T angle brackets mean in Java?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

In Java, the notation <T> in angle brackets represents a generic type parameter. Generics were introduced in Java 5 to allow for stronger type checks at compile-time, enabling the creation of classes, interfaces, and methods that operate on specified types without writing additional code for each type. This feature aims to eliminate the need for casts and enhance code reusability.

Technical Explanation

Generic Types

Java's generics are a part of its type system that enables parameterization of types. When a class or method operates on a generic type, it is specified using a notation like <T>, where T is a type parameter. This parameter can be replaced with any non-primitive data type, providing a means to use code more flexibly and safely.

Type Parameter Naming Conventions

While you can name type parameters as you like, there are common conventions:

  • T - Type
  • E - Element (used in collections)
  • K - Key
  • V - Value
  • N - Number

How Generics Work

Generics enforce type safety by ensuring that you handle only intended types. Generic code applies compile-time checks, minimizing the need for runtime checks and type casting.

Example of a Generic Class

java
1public class Box<T> {
2    private T item;
3
4    public void setItem(T item) {
5        this.item = item;
6    }
7
8    public T getItem() {
9        return item;
10    }
11}

In this example, the Box class works with any type T. If you create an instance of Box with an Integer type, the code looks like this:

java
Box<Integer> integerBox = new Box<>();
integerBox.setItem(10);
Integer item = integerBox.getItem();

Example with Generic Methods

A generic method works within the context of a class and can be independent of class-level type parameters:

java
1public class Util {
2    public static <T> void printArray(T[] array) {
3        for (T element : array) {
4            System.out.println(element);
5        }
6    }
7}

Advantages of Generics

  • Type Safety: Generics provide compile-time type checking, reducing runtime errors.
  • Code Reusability: Write a single class or method applicable for different types.
  • Elimination of Casts: Explicit type casting becomes unnecessary.

Limitations and Considerations

  • Primitive Types Unsupported: You cannot use primitives like int, char. Use wrapper classes (Integer, Character).
  • Type Erasure: Java generics rely on type erasure, meaning generic type information is erased at runtime. This limits runtime type inspections of generics.

Practical Usage in Collections

Java Collections framework extensively uses generics. For example, ArrayList<T> ensures that only elements of type T are stored within.

Example:

java
ArrayList<String> stringList = new ArrayList<>();
stringList.add("Hello");
// stringList.add(10); // Compile-time error since 10 is not a String

Summary Table

FeatureDescription
Type ParametersDenoted by angle brackets <T>, represents a placeholder for a concrete type.
PurposeAllow code to be written generically to work with different types, enforcing type safety and reducing redundancy.
ConventionsUse T for Type, E for Element, K for Key, V for Value, N for Number.
Compile-Time CheckingProvides stricter type checks at compile time, reducing runtime exceptions.
LimitationsDoes not support primitive types directly and uses type erasure which removes type information at runtime, limiting certain reflective operations.
Syntax Exampleclass Box<T> &#123; ... &#125; Box<Integer> intBox = new Box<>();
CollectionsUsed extensively for type-safe collections, e.g., ArrayList<String> ensures only strings are added.

Additional Considerations

Wildcards

Java generics support wildcards, allowing more flexible generic parameters:

  • <?>: Unknown type.
  • <? extends T>: Any type that is a subtype of T.
  • <? super T>: Any type that is a supertype of T.
Example with Wildcards
java
1public void processItems(List<? extends Number> list) {
2    for (Number number : list) {
3        // process each number
4    }
5}

Bounded Type Parameters

You can restrict the types that can be used as arguments for a parameterized type using bounded type parameters:

java
1public class NumberBox<T extends Number> {
2    private T number;
3    // implementation
4}

In this case, instances of NumberBox can only be created for classes that are subtypes of Number.

Embedding generics effectively into your Java applications can lead to more robust, flexible, and readable code by clearly defining the types expected and used throughout your program.


Course illustration
Course illustration

All Rights Reserved.