Java Generics

Generics In Java can be understood by the figure below, as you can see there is a cup and in which “T” denotes what type of entity does it contain. Let’s say, it may contain tea or coffee or milk or water. So we can say the cup is a container that can contain any type of entity. Same as in the case of Java, a Generic container consists of various types of object. For example. Let’s say we are not sure about the data type to be used in the code, so there we will make class or method to be of the generic type as shown below:

Class_name <data type> reference_name = new Class_name<data type>();
Java Generics

Generic means “Parameterized Types” which was introduced by JDK 1.5.0. A class, Interface, or method that operates on a parameterized type is called Generic class or generic method or generic Interface. With Generics we can define an algorithm once without any specific Data Type and here Data Types are defined as a parameter. In case of Generics, all casts are automatic and implicit. When declaring an instance of a Generic type, the Type Argument is passed to type parameter.

Note: In Java, Generic Type should always be an Object type, it cannot use Primitive Data Types.

Generic V/S Object

  • Casting is implicit with generic type but with Object type casting is required
  • Generic results in compilation error with incorrect data whereas in case of Object exception is generated

Generic Class

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

Example

Output

Type Parameters

The common type parameters are as follows:

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

Generic Method

Just like we have generic class, we can also create generic methods that can accept arguments of any type. Let’s understand this with the help of an example.

Example

Output

WildCard In Java Generics

This “?” symbol represents wildcard element, which means “Any Type”. Let’s understand this by the example given below

Advantages of using Generics

  • Here there is Stronger type check at compile time
  • By using Generics, Code Reusability is increased
  • All casts are automatic and implicit
  • Type Safety, which means a compile-time error will be generated if any other data type values are passed instead of the declared one

Octocat - CodedBug github
For more examples of Generics In Java refer codedbug GitHub repo

Leave a Reply

Contact Us
close slider
Contact Us

How can we help you with?