Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What is Generics in Java?

What is Generics in Java?

Generics in Java was introduced back in 2004 as a new feature of the Java programming language and was part of the JDK 5 release. It is most widely used along with the Java collections framework. As of today it is one of the most prominent and sought after feature of the Java programming language.

Generic Java was found by four individuals namely Gilad Bracha, Martin Odersky, David Stoutamire and Philip Wadler in 1998. It was an extension of the Java language that supported generic types. It was meant to achieve two main goals which are:

  1. Type safety
  2. Code reusability

Definition Of Generics in Java

Generics can be defined as a way to achieve code reusability by defining generic classes, interfaces, constructors and methods that can be used with different data types and also achieve type safety by declaring the data type being used in the implementation before-hand, therefore eliminating the chances of a run-time error.

How are generics implemented in Java?

Generics are implemented using angular brackets “”. The brackets enclose the type parameter “T” within them. Example, . The type parameter “T” is a place holder which indicates that a data type will be assigned to it at run time. For example, a generic class will be defined as:

public class MyGenericClass {…}

The following are the standard type parameters:

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

S, U, V and so on are used to define second, third and fourth parameters respectively in case multi-parameter are being used.

Understanding Generics in Java

By now you might be wondering what is type safety and how does it work? Or how are generic classes, interfaces, constructors and methods any different from our regular classes and methods that make them reusable? Let’s find out.

Java being a statically typed language requires you to declare the “type” that is the data type of the value being held by the variable before using it.

Example: String myString =”eduCBA”;

Here “String” is the data type, “myString” is the variable that will hold a value whose type is String.

Now, if you try to pass a Boolean value in place of a string, for example:

String myBooleanStr = true;

You will immediately get a compile-time error stating “Type mismatch: cannot convert from boolean to String”.

How do we achieve code reusability with generics?

Now, let us define a regular method:

public static void welcome(String name){
System.out.println("welcome to " + name);
}

This method can be invoked only by passing a string parameter. For example:

welcome(“eduCBA”);

Its output will be “welcome to eduCBA”.

However, you cannot invoke this method bypassing any other data types such as integer or boolean. If you try to do that, you will be prompted with a compile-time error stating “The method welcome(String) in the type Runner is not applicable for the arguments (boolean)”. Meaning you cannot pass any other data type to a method which only accepts a string as a parameter.

This also means if you wish to invoke a similar method for a different data type then you will have to write a new method that accepts the required data type as a parameter. This feature of re-writing methods with parameters of different data types is also known as method overloading. The major drawback of this is it increases the size of your code.

However, we could also use Generics to re-write the above method and use it for any data type we require.

Defining a Generic method:

public static void welcome(T t){
System.out.println("it is " + t);
}

Note: Here “t” is an object of type T. T will be assigned the data type that is being used to invoke the method.

Now you can reuse this method by invoking it for a string when required or a boolean or an integer or any other data type.

welcome("educate");
Integer Myint = 1;
welcome(Myint)
welcome(true);

The above statements will provide the below output:

It is Educa
It is 1
That is true

Therefore, by using generics here we are able to re-use our method for different data types.

How do we achieve type safety using Generics?

One of the major differences between Arrays and Collection is that Arrays can store only homogeneous data, whereas Collections can store heterogeneous data. That is Collections can store any user-defined data type/ objects.

NOTE: Collections can only hold objects (user-defined data type) and not a primitive data type. In order to work with primitive data, type collections make use of wrapper classes.

Now, let us consider an Arraylist.

ArrayList myList = new ArrayList();

Let us add data of type String, Integer and Double to the ArrayList object.

myList.add("eduCBA");
myList.add(1);
myList.add(5.2);

On printing the ArrayList object we can see that it holds the following values: [eduCBA, 1, 5.2].

Now if you wish to retrieve these values into variables then, you will need to typecast them.

String someStr = (String)myList.get(0);
Integer someInt = (Integer)myList.get(1);
Double someFlt = (Double)myList.get(2);

In case you do not typecast, you will be prompted with a compile-time error stating “Type mismatch: cannot convert from Object to String”.

From this, you can conclude that while retrieving the objects from your ArrayList, you need to typecast it to their respective types. The question that arises here is how will you know which data type to typecast it to? In real time your ArrayList will contain thousands of record and typecasting it to different data types for every individual object will not be an option. You might end up typecasting it to the wrong data type. What happens then?

This time you will not get a compile time error but will throw a runtime error stating “Exception in thread “main” java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.String at com.serviceClasess.Runner.main(Runner.java:43)”.

Since we can’t guarantee the type of data present inside a collection (in this case ArrayList), they are considered not safe to use with respect to type. This is where generics come into play to provide type safety.

Using ArrayList with Generics:

ArrayList myList = new ArrayList();

Notice that inside angular brackets “”, String type is specified which means this particular implementation of ArrayList can only hold String type data. If you try to add any other data type to it, it will simply throw compile time error. Here you have made your ArrayList type-safe by eliminating its chance of adding a different data type other than “String”.

Now that you have specified the data type that is allowed to be added to your collection with the help of generics, you no longer need to typecast it while retrieving your data. That is you can simply retrieve your data by writing:

String someStr = myList.get(0);

How does Generics in Java make working so easy?

It helps make your collections type safe thus making sure your code doesn’t fail at a later point due to a run time exception. It also saves the coder from having to typecast every object in the collection making the code development faster and easier. By making use of generic classes and methods one can also reuse the code as per ones required data type during implementation.

What else can you do with Generics in Java?

So far we have seen how we can achieve type safety and code reusability with generics. Now let us look at the other features generics provide. They are:

  1. Bounded & multiple bounded types
  2. Type wildcards

Bounded Type: In case of a bounded type the data type of a parameter is bounded to a particular range. This is achieved with the help of the “extends” keyword.

For Example, let us consider a generic class with a bounded type parameter that extends Runnable interface:

class myGenericClass{}

Now, while creating its object in another class:

myGenericClass myGen = new myGenericClass();

The above statement will execute perfectly without any errors. That is in case of the bounded type you can pass the same class type or its child class type. Also, you can bind the parameter type to an interface and pass its implementations when invoking it, as in the case of our example above.

What happens if you try to use any other type of parameter?

myGenericClass myGen = new myGenericClass();

In the above case, you will get a compile-time error stating “Bound mismatch: The type Integer is not a valid substitute for the typecast of the type myGenericClass”.

Multiple bounded types: In case of multiple bounded types we can bind the parameter data type to more than one type. For example,

Class myGeneric{}

In this case, you can pass any type which extends Number class and implements Runnable interface. However, when using multiple bounded types few things should be noted:

  1. We cannot extend more than one class at a time.
  2. We can extend any number of interfaces at a time that is there is no limit for interfaces.
  3. The class name should always come first followed by the interface name if not it will result in a compile-time error.

Type Wildcards: They are represented by “?” – question mark symbol.  It makes use of two main keywords:

extends (to define upper bound) and super (to define lower bounds).

For example,

ArrayList extends T> al

This ArrayList object “al” will hold any data of type T and all its subclasses.

ArrayList super T> al

This ArrayList object “al” will hold any data of type T and all its superclasses.

Advantages of Generics in Java

1. Flexibility: Generics provides our code with the flexibility to accommodate different data types with the help of generic classes and methods.

2. Code Maintenance and Reusability: Due to generic classes and methods one need not re-write the code, in case of a change in requirements at a later stage making the code easier to maintain and reuse.

3. Type safety: Provides type safety to the collection framework by defining the data type the collection can hold beforehand and eliminating any chances of failure at run time due to ClassCastException.

4. Eliminating the need to typecast: Since the data types being held by the collections are already determined one need not typecast it at the time of retrieval. This reduces the length of the code and also reduces a coder’s effort.

Generics in Java skills

In order to work with Generics, you should be well versed with the basics of Java. You should understand how type checking and type casting works. Thorough knowledge of other concepts such as method overloading, the relationship between parent and child classes, interfaces and their implementations are necessary. Also understanding the difference between primitive data types (system defined data type) and objects (user-defined data type) is crucial when it comes to working with the collection framework.

Why should we use Generics in Java?

Using generics makes our code more maintainable as it reduces the need to rewrite data type specific code every time there is a change in requirement. By using generics bounded type you could restrict the data type and at the same time provide flexibility to your code by defining its range. Your code is less likely to fail at a later point as it provides type safety making your code less error-prone.

Scope for Generics in Java

Generics scope is limited to compile time. That means generics concept is applicable only at compile time but not at run time. For Example,

ArrayList myList = new ArrayList();

ArrayList myList = new ArrayList();

ArrayList myList = new ArrayList();

ArrayList myList = new ArrayList();

Here all the above four statements are one and the same. They will allow the addition of any type of data to the list object.

Conclusion

Generics makes coding easy for a coder. It diminishes the chances of encountering ClassCastException at run time by providing strong type-checking. Completely eliminates the need for type casting which means less code needs to be written. Provides us with the feasibility to develop generic algorithms that are independent of the data type they are working with.

Recommended Articles

This has been a guide to What is Generics in Java?. Here we discussed the Skills, Scope, working, Understanding and Advantage of Generics in Java. You can also go through our other suggested articles to learn more –

  1. What is Common Gateway Interface
  2. How to Install Java 8
  3. what is soapUI
  4. What is JavaScript?

The post What is Generics in Java? appeared first on EDUCBA.



This post first appeared on Best Online Training & Video Courses | EduCBA, please read the originial post: here

Share the post

What is Generics in Java?

×

Subscribe to Best Online Training & Video Courses | Educba

Get updates delivered right to your inbox!

Thank you for your subscription

×