Core Java Concepts and Syntax

Learn about Generics in Java

Learn about Generics in Java

Introduction

Generics are a type of programming language feature that allows you to provide multiple independently replaceable parameters to a function.
We can create Java Generics classes, interfaces, and methods that are reusable across different types of data (objects). By doing this, we can reuse our code.

What are Generics In Java?

Java Generics were introduced in J2SE 5 to handle type-safe objects. At compile time, it detects bugs and makes the code more stable.

Before generics, any object could get included in the collection. With generics, Java programmers must store specific kinds of objects.

By using generic methods and generic classes, programmers can specify sets of related methods, or sets of related types, through a single method declaration. Additionally, generics offer compile-time type safety, which makes it possible for programmers to catch invalid types during compilation.

Generic Java methods can get used for sorting arrays of objects, such as integer arrays, double arrays, string arrays, etc. We can execute the generic method using array elements of Integer arrays, Double arrays, String arrays, etc.

Types of Java Generics

Generic Methods

The generic method declaration can accept different types of arguments. The compiler handles each method call according to the arguments passed to the generic method. The rules for defining generic methods are as follows:

  • During the declaration of generic methods, angle brackets must get used to delimit type parameters (< and >) before the method's return type.
  • There are several type parameter sections, each containing one or more type parameters separated by commas. Type parameters, or type variables, are identifiers that specify generic types.
  • As placeholders for the actual type arguments, the type parameters can define a generic method's return type.
  • Generic methods get declared like other methods. Note that type parameter can only represent reference types, not primitive data types (such as int, double, and char).

Generic Class in Java

Unlike non-generic class declarations, generic class declarations include type parameters after the class name.

In generic classes, type parameters are separated by commas, just like generic methods. Classes that accept one or more parameters refer to as parameterized classes or parameterized types.

Example

Following is an example of a generic class:

public class Box<T> {
  private T t;

  public void add(T t) {
      this.t = t;
  }

  public T get() {
      return t;
  }

  public static void main(String[] args) {
      Box<Integer> integerBox = new Box<Integer>();
      Box<String> stringBox = new Box<String>();
   
      integerBox.add(new Integer(25));
      stringBox.add(new String("Hello Java"));

      System.out.println("Integer Value :%d\n", integerBox.get());
      System.out.println("String Value :%s\n", stringBox.get());
  }
}
Output:

Integer Value:25
String Value: Hello Java

write your code here: Coding Playground

Type Parameters

To learn java generics thoroughly, you must understand the naming conventions for type parameters. Here are some common type parameters:

T - Type

E - Element

K - Key

N - Number

V - Value

Advantages of Java Generics

1. Code Reusability

The generics feature in Java allows us to write code that works with various data types.

2. Compile-time Type Checking

The Generics type parameter specifies what data type is being used in the program.

3. Used with Collections

In Java, generics are used to implement the collections framework.

Conclusion

Java Generics simplifies and reduces error-prone programming tasks for Java programmers. First, generics ensure type correctness at compile time, and second, they enable the implementation of generic algorithms without causing any additional overhead.