Tutorials / Tech blog / Geek Zone

Latest Posts

JAVA :: Generics

The Java Generics feature was introduced in J2SE 5 to deal with type-safe objects. It adds a way to specify concrete types to general purpose classes and methods that operated on Object before.

Generics helps us to create a single class, which can be useful to operate on multiple data types.Generics ensures compile-time type safety that helps programmers to catch invalid types during compile time. (e.g. ClassCastException which was was common while working with collection classes)

Generic Method

One can write a generic method declaration that can be called with variety of argument types. Based on the type of argument used to invoke this generic method, the compiler will handle each call appropriately. This flexibility allows the possibility of creating common libraries (utilities) which can be leveraged as per users need. (e.g. Comparable Interface) .

Let's try writing a Generic Method...

  • Method declaration consist of a type parameter section which precedes the method's return type. It's delimited by angle brackets. It's also known as type variable.
  • The type parameters can be used to declare the return type and act as placeholders for the types of the arguments passed to the generic method, which are known as actual type arguments.
Note :- Type Parameters can only represent reference types.

The commonly type parameters are as follows:
  • T - Type
  • E - Element
  • K - Key
  • N - Number
  • V - Value

Bounded Type Parameters

Java Generics Upper Bounded Wildcard
Java Generics Unbounded Wildcard
Java Generics Lower bounded

Subtyping using Generics Wildcard

List<? extends Integer> integerList = new ArrayList<>();
List<? extends Number>  numberList = integerList;  // Valid as List<? extends Integer> is a subtype of List<? extends Number>

No comments:

Post a Comment