What are Generics in Java?

Java Generics is a set of related methods or a set of similar types. Generics allow types Integer, String, or even user-defined types to be passed as a parameter to classes, methods, or interfaces. Generics are mostly used by classes like HashSet or HashMap.


Advantages of using generics

  • Generics ensure compile-time safety which allows the programmer to catch the invalid types while compiling the code.

  • Java Generics helps the programmer to reuse the code for whatever type he/she wishes. For instance, a programmer writes a generic method for sorting an array of objects. Generics allow the programmer to use the same method for Integer arrays, Double arrays, and even String arrays.

  • Another advantage of using generics is that Individual typecasting isn’t required. The programmer defines the initial type and then lets the code do its job.

  • It allows us to implement non-generic algorithms.

svg viewer

Constraints

  • Java Generics does not support sub-typing.

  • You cannot create generic arrays in Java Generics.


Types of Java Generics

  • Generic method: Generic Java method takes a parameter and returns some value after performing a task. It is exactly like a normal function, however, a generic method has type parameters which are cited by actual type. This allows the generic method to be used in a more general way. The compiler takes care of the type of safety which enables programmers to code easily since they do not have to perform long, individual type castings.

  • Generic classes: A generic class is implemented exactly like a non-generic class. The only difference is that it contains a type parameter section. There can be more than one type of parameter, separated by a comma. The classes, which accept one or more parameters, ​are known as parametrized classes or parameterized types.

Examples

1. Single generic method

This example shows how to print different types of arrays using the single Generic method:

class GenericMethodTest {
// generic method printArray
public static < E > void printArray( E[] inputArray ) {
// Display array elements
for(E element : inputArray) {
System.out.printf("%s ", element);
}
System.out.println();
}
public static void main(String args[]) {
// Create arrays of Integer, Double and Character
Integer[] integerArray = { 5, 4, 3, 2, 1 };
Double[] doubleArray = { 1.21, 22.12, 13.32 };
Character[] characterArray = { 'Y', 'o', 'u', ' ', 'a', 'r', 'e', ' ', 'a','w','e','s','o','m','e' };
System.out.println("integerArray contains:");
printArray(integerArray); // pass an Integer array
System.out.println("\ndoubleArray contains:");
printArray(doubleArray); // pass a Double array
System.out.println("\ncharacterArray contains:");
printArray(characterArray); // pass a Character array
}
}

2. Generic class

This example shows how to define a generic class:

class container<T> {
private T obj1;
public void add(T obj1) {
this.obj1 = obj1;
}
public T get() {
return obj1;
}
public static void main(String[] args) {
container<Integer> integerContainer= new container<Integer>();
container<String> stringContainer = new container<String>();
integerContainer.add(new Integer(7));
stringContainer.add(new String("You are awesome"));
System.out.printf("Integer Value :%d\n\n", integerContainer.get());
System.out.printf("String Value :%s\n", stringContainer.get());
}
}

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved