Java - Generic Class

1 - About

generic class

All instances of a generic class have the same run-time class, regardless of their actual type parameters.


List<String> l1 = new ArrayList<String>();
List<Integer> l2 = new ArrayList<Integer>();
System.out.println(l1.getClass() == l2.getClass());


true

A class generic has the same behavior for all of its possible type parameters; the same class can be viewed as having many different types.

The class java.lang.Class is generic. It has a type parameter T. Class<T> - The type of String.class is Class<String>

3 - Syntax

A generic class is defined with the following format:


class name<T1, T2, ..., Tn> { /* ... */ }

where:

  • the angle brackets (Diamond) (<>) is the type parameter section
  • T1, T2, …, and Tn are the type parameters (also called type variables). T stands for “Type”. The type variable, T, that can then be used anywhere inside the class.

4 - Initialization


Box<Integer> integerBox = new Box<Integer>();
Box<Integer> integerBox = new Box<>(); // The parameters are optional after the new keyword because it can be inferred.
// Use Class<?> if the class being modeled is unknown.

5 - Raw Type

If the actual type argument is omitted, you create a raw type of Box<T>:


Box rawBox = new Box();
// Same as
Box<Object> rawBox = new Box<>()

If you assign a raw type to a parameterized type, you get a warning:


Box rawBox = new Box();           // rawBox is a raw type of Box<T>
Box<Integer> intBox = rawBox;     // warning: unchecked conversion

6 - Example

6.1 - Class

A Generic version of a class ClassName. The @param <T> is the type of the value being boxed


public class ClassName<T> {
    
    // T stands for "Type"
    private T t;
    public void set(T t) { this.t = t; }
    public T get() { return t; }
    
}


Data Science
Data Analysis
Statistics
Data Science
Linear Algebra Mathematics
Trigonometry

Powered by ComboStrap