Generics in Java with Examples

Generics in Java with Examples

Generics allows us to pass the generic types as parameters to a class or methods.
Example: class A<T>

Generics Advantages:

  • Stronger type checking
  • Casting elimination

Type Parameter Naming Conventions:

  • E – Element
  • K – Key
  • V – Value
  • N – Number
  • T – Type

There are various ways of using Generics, In this post let us see, generics with

  • Upper Bounded Wildcards
  • Unbounded Wildcards
  • Lower Bounded Wildcards

First let us see an example of using generics along with the class

Output:

Now let us see another example of using Generics with Key and Value along with Upper Bound Wildcards, Unbounded Wildcard and Lower Bound Wildcards.

Wildcards usually starts with “?” – Example: List<? extends Number>

Upper Bound Wildcards
Used to relax restrictions on a variable. In the below example we have used upperBound wildcard to pass integers, calculate sum of it and change it double and print it.

Unbounded Wildcards:
Unbounded wildcards is used for unknown types. It can be of any type, Integer or String or object etc..

Lower Bound Wildcards:
Lower Bound Wildcards restricts the unknown type to be specific. (Upper Bound relaxes the restrictions)

 

 

Read More