In this tutorial, we will learn about Java Generics, how to make generics class and techniques, and its advantages with the help of examples.
The Java Generics allows us to make a single class, interface, and strategy that can be used with various types of data (objects).
This helps us to reuse our code.
Note: Generics does not work with primitive types (int, float, char, etc).
In this article, you will learn-
Java Generics Class
We can make a class that can be used with any type of data. Such a class is known as Generics Class.
Here’s is the means by which we can make a generics class in Java:
Example: Create a Generics Class
class Main {
public static void main(String[] args) {
// initialize generic class
// with Integer data
GenericsClass<Integer> intObj = new GenericsClass<>(5);
System.out.println("Generic Class returns: " + intObj.getData());
// initialize generic class
// with String data
GenericsClass<String> stringObj = new GenericsClass<>("Java Programming");
System.out.println("Generic Class returns: " + stringObj.getData());
}
}
// create a generics class
class GenericsClass<T> {
// variable of T type
private T data;
public GenericsClass(T data) {
this.data = data;
}
// method that return T type variable
public T getData() {
return this.data;
}
}
Output
Generic Class returns: 5
Generic Class returns: Java Programming
In the above example, we have made a generic class named GenericsClass. This class can be used to work with any type of data.
class GenericsClass<T> {...}
Here, T used inside the point section <> demonstrates the type parameter. Inside the Main class, we have made two objects of GenericsClass
- intObj – Here, the type parameter T is replaced by Integer. Now, the GenericsClass works with integer data.
- stringObj – Here, the type parameter T is replaced by String. Now, the GenericsClass works with string data.
Java Generics Method
Like the generics class, we can likewise make a technique that can be used with any type of data. Such a class is known as Generics Method.
Here’s is the means by which we can make a generics class in Java:
Example: Create a Generics Method
class Main {
public static void main(String[] args) {
// initialize the class with Integer data
DemoClass demo = new DemoClass();
// generics method working with String
demo.<String>genericsMethod("Java Programming");
// generics method working with integer
demo.<Integer>genericsMethod(25);
}
}
class DemoClass {
// creae a generics method
public <T> void genericsMethod(T data) {
System.out.println("Generics Method:");
System.out.println("Data Passed: " + data);
}
}
Output
Generics Method:
Data Passed: Java Programming
Generics Method:
Data Passed: 25
In the above example, we have made a generic method named genericsMethod.
public <T> void genericMethod(T data) {...}
Here, the sort parameter <T> is inserted after the modifier public and before the return type void.
We can call the generics technique by putting the genuine sort <string> and <integer> inside the section before the strategy name.
demo.<String>genericMethod("Java Programming");
demo.<Integer>genericMethod(25);
Note: We can call the generics method without including the type parameter. For example,
demo.genericsMethod("Java Programming");
For this situation, the compiler can coordinate the sort parameter dependent on the worth passed to the strategy.
Bounded Types
In general, the type parameter can acknowledge any data types (except primitive types).
However, if we need to use generics for some particular sorts, (for example, acknowledge data of number types) just, at that point we can use bounded sorts.
On account of bound types, we use the extends watchword. For instance,
<T extends A>
This means T can only accept data that are subtypes of A.
Example: Bounded Types
class GenericsClass <T extends Number> {
public void display() {
System.out.println("This is a bounded type generics class.");
}
}
class Main {
public static void main(String[] args) {
// create an object of GenericsClass
GenericsClass<String> obj = new GenericsClass<>();
}
}
In the above example, we have made a class named GenericsClass. Notice the expression, notice the expression
<T extends Number>
Here, GenericsClass is made with bounded sort. This means GenericsClass can just work with data types that are offspring of Number (Integer, Double, etc).
However, we have made an object of the generics class with String. For this situation, we will get the accompanying error.
GenericsClass<String> obj = new GenericsClass<>();
^
reason: inference variable T has incompatible bounds
equality constraints: String
lower bounds: Number
where T is a type-variable:
T extends Number declared in class GenericsClass
Advantages of Java Generics
1. Code Reusability
With the help of generics in Java, we can write code that will work with various sorts of data. For instance,
public <T> void genericsMethod(T data) {...}
Here, we have made a generics strategy. This equivalent strategy can be used to perform operations on integer data, string data, etc.
2. Compile time Type Checking
The type parameter of generics gives data about the type of information used in the generics code. For instance,
// using Generics
GenericsClass<Integer> list = new GenericsClass<>();
Here, we realize that GenericsClass is working with Integer data only.
Presently, if we attempt to pass data other than Integer to this class, the program will create an error accumulate time.
3. Used with Collections
The collections framework uses the concept of generics in Java. For instance,
// creating a string type ArrayList
ArrayList<String> list1 = new ArrayList<>();
// creating a integer type ArrayList
ArrayList<Integer> list2 = new ArrayList<>();
In the above example, we have used the same ArrayList class to work with different types of data.
Similar to ArrayList, other collections (LinkedList, Queue, Maps, and so on) are also generic in Java.
Thanks for reading! We hope you found this tutorial helpful and we would love to hear your feedback in the Comments section below. And show us what you’ve learned by sharing your photos and creative projects with us.