What is Generics in Java? – A Beginners Guide

Published on Jun 19,2019 9.7K Views
A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop. A tech enthusiast in Java, Image Processing, Cloud Computing, Hadoop.

What is Generics in Java? – A Beginners Guide

edureka.co

Consider an example where you have to make a list of the living things in a locality. It doesn’t matter whether it’s a human being, an animal or a plant. All that matters is a living thing. In this case, you would group them all as “Living Things” and not categorize them. Similarly, when you have to store some data, what matters to you is the content and not the datatype, and that’s where you use Generics. Generics in Java is a language feature that allows the use of generic types and methods.

Below is the list of topics that I will be covering in this article:

What is Generics in Java?

Generics is a term that denotes a set of language features related to the definition and use of Generic types and methods. Java Generic methods differ from regular data types and methods. Before Generics, we used the collection to store any type of objects i.e. non-generic. Now, Generics force the Java programmer to store a specific type of objects.

Now that you know what is Generics in Java, let’s move further and understand why do you need Java Generics.

Why Java Generics?

If you look at the Java collection framework classes, then you will observe that most classes take parameter/argument of type Object. Basically, in this form, they can take any Java type as argument and return the same object or argument. They are essentially heterogeneous i.e. not of a similar type.

Sometimes in the Java application, the data type of the input is not fixed. The input can be an integer, a float or  Java string. In order to assign the input to the variable of the right datatype, prior checks had to be conducted. In the traditional approach, after taking the input, the datatype of the input was checked and then was assigned to the variable of the right datatype. When this logic was used, the length of the code and execution time was increased. To avoid this, Generics were introduced. When you use Generics, the parameters in the code is checked at compile time automatically and it sets the datatype by default. So this is where you need the concept of generics in Java.

Now that you have gained some insights on Generics, let’s move ahead and look at the various ways how Generics can be applied to the source code.

Types of Java Generics

There are 4 different ways Generics can be applied to in Java and they are as follows:

  1. Generic Type Class
  2. Generic Interface
  3. Generic Method
  4. Generic Constructor

Now let’s understand how generics can be applied to type class in depth.

1. Generic Type Class

A class is said to be Generic if it declares one or more type variables. These variable types are known as the type parameters of the Java Class. Let’s understand this with the help of an example. In the below example, I will create a class with one property x and type of the property is an object.

class Genericclass{
private Object x;
public void set(Object x) { this.x = x; }
public Object get() { return x; }
}

Here, once you initialize the class with a certain type, the class should be used with that particular type only. E.g. If you want one instance of the class to hold the value x of type ‘String‘, then programmer should set and get the only String type. Since I have declared property type to Object, there is no way to enforce this restriction. A programmer can set any object and can expect any return value type from get method since all Java types are subtypes of Object class.

To enforce this type of restriction, we can use generics as below:

class Genericclass<X> {
//T stands for "Type"
private T x;
public void set(T x) { this.x = x; }
public T get() { return x; }
}

Now you can be assured that class will not be misused with wrong types. A simple example ofGenericclass”  looks like as shown below:

Genericclass<String> instance = new Genericclass<String>();
instance.set("Edureka");
instance.set(10); //This will raise compile time error

So that’s how it works. This analogy is true for the interface as well. Let’s quickly look at an example to understand, how generics type information can be used in interfaces in java.

2. Generic Interface

An interface in Java refers to the abstract data types. They allow Java collections to be manipulated independently from the details of their representation. Also, they form a hierarchy in object-oriented programming languages. Let’s understand how generic type can be applied to interfaces in Java.

//Generic interface definition
interface GenericInterface<T1, T2>
{
T2 PerformExecution(T1 x);
T1 ReverseExecution(T2 x);
}

//A class implementing generic interface
class Genericclass implements GenericInterface<String, Integer>
{
public Integer PerformExecution(String x)
{
//execution code
}
public String ReverseExecution(Integer x)
{
//execution code
}
}

I hope you were able to understand how Generics can be applied to type class and interfaces. Now let’s delve deeper into this article and understand how it is helpful for methods and constructors.

3. Generic Methods

Generic methods are much similar to generic classes. They differ from each other in only one aspect that the scope or type information is inside the method only. Generic methods introduce their own type parameters.

Let’s understand this with an example. Below is an example of a generic method which can be used to find all the occurrences of type parameters in a list of variables.

public static <T> int countAllOccurrences(T[] list, T element) {
int count = 0;
if (element == null) {
for ( T listElement : list )
if (listElement == null)
count++;
}
else {
for ( T listElement : list )
if (element.equals(listElement))
count++;
}
return count;
}

If you pass a list of String to search in this method, it will work fine. But if you try to find a Number in the list of String, it will give compile time error.

This analogy is similar to the constructor as well. Let’s take an example for the generic constructor and understand how it works.

4. Generic Constructor

A constructor is a block of code that initializes the newly created object. A constructor resembles an instance method in Java but it’s not a method as it doesn’t have a return type. The constructor has the same name as the class and looks like this in Java code. Now let’s take an example and understand how it works.

class Dimension<T>
{
private T length;
private T width;
private T height;

//Generic constructor
public Dimension(T length, T width, T height)
{
super();
this.length = length;
this.width = width;
this.height = height;
}
}

In the above example, Dimension class’s constructor has the type information. So you can have an instance of dimension with all attributes of a single type only. So this is how you can use generics type constructors. I hope you understood the types of generics in Java.

Now let’s move further and look at the advantages of Generics in Java.

Advantages of Generics in Java

1. Code Reusability

You can compose a strategy or a class or an interface once and use for any type or any way that you need.

2. Individual Types Casting isn’t required

Basically, you recovered information from ArrayList every time, you need to typecast it. Typecasting at each recovery task is a major migraine. To eradicate that approach, generics were introduced.

3. Implementing a non-generic algorithm

It can calculate the algorithms that work on various sorts of items that are type safe as well.

That was all about the advantages of Java Generics. With this, we come to the end of this article on Generics in Java. I hope you found it informative and helped you in understanding Java Generics.

Check out the Java Training by Edureka, a trusted online learning company with a network of more than 250,000 satisfied learners spread across the globe. We are here to help you with every step on your journey, for becoming a besides this java interview questions, we come up with a curriculum which is designed for students and professionals who want to be a Java Developer. The course is designed to give you a head start into Java programming and train you for both core and advanced Java concepts along with various Java frameworks like Hibernate & Spring.

Got a question for us? Please mention it in the comments section of this “Generics in Java” article and we will get back to you as soon as possible.

Upcoming Batches For Java Course Online
Course NameDateDetails
Java Course Online

Class Starts on 21st December,2024

21st December

SAT&SUN (Weekend Batch)
View Details
Java Course Online

Class Starts on 1st March,2025

1st March

SAT&SUN (Weekend Batch)
View Details
BROWSE COURSES
REGISTER FOR FREE WEBINAR Building Robust Applications with Spring Framework