Write Less Code with Generics

Stefano Troìa
The Startup
Published in
3 min readNov 20, 2019

--

Photo by Soraya Irving on Unsplash

Generics methods and classes allow programmers to write a single method or class gentrified to work with different types.

We use them every day think to List<T>, Stream<T>, Map<K, V>

A generic class is a normal class with the class name followed by a type parameter section. These classes are known as parameterized classes or parameterized types because they accept one or more parameters.

Features:

  • Type-safety: We can hold only a single type of object in generics.
  • Typecasting is not required: There is no need to typecast the object.
  • Compile-Time Checking: It is checked at compile time so the problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.

Type parameters naming convention:

  • T type
  • E element
  • K Key
  • N Number
  • V value

Wildcards

The ? as we know is the wildcard symbol, it indicates any type. If we write <? extends Number>, we are accepting any child class of Number, e.g., Integer, Float, and double.

--

--