Introduction to Generics in Java
Generics in Java are the advanced feature that helps to achieve code reusability and type safety. The code reusability functionality in java is managed by defining generic classes, interfaces, constructors, and methods. Generic uses the data type declaration for a type safety feature that helps to eliminate the run time error. The generic in java is implemented using the angular bracket ‘<>’ symbol, and the type parameter is defined in the bracket. The Type parameters include ‘T’ for type, ‘E’ for element, ‘N’ for number, ’K’ for the key and ‘V’ for value. An example of a generic class with a Type T parameter is ‘public class DemoGenericClass<T> {…}.’
What is 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 achieve type safety by declaring the data type used in the implementation beforehand 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. For Example, <T>. The type parameter “T” is a placeholder, indicating that a data type will be assigned at run time.
For example, a generic class will be defined as:
Code:
public class MyGenericClass<T> {…}
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 the case of multi-parameters.
Understanding Generics in Java
By now, you might be wondering what is a type of safety is and how does it work? Or how are generic classes, interfaces, constructors, and methods different from our regular classes and methods that make them reusable?
Java, a statically typed language, requires you to declare the “type” that is the data type of the value held by the variable before using it.
Example:
Code:
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:
Code:
String myBooleanStr = true;
You will immediately get a compile-time error stating, “Type mismatch: cannot convert from boolean to String.”
Output:
How do we Achieve Code Reusability with Generics?
Now, let us define a regular method:
Code:
public static void welcome(String name){
System.out.println("welcome to " + name);
}
This method can be invoked only by passing a string parameter.
Code:
welcome("eduCBA");
Its output will be “welcome to eduCBA.”
However, you cannot invoke this method bypassing 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).” This means you cannot pass any other data type to a method that only accepts a string as a parameter.
Output:
If you wish to invoke a similar method for a different data type, you must 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:
Code:
public static <T> void welcome(T t){
System.out.println("it is " + t);
}
Now you can reuse this method by invoking it for a string when required, a boolean, an integer, or any other data type.
Code:
welcome("educate");
Integer Myint = 1;
welcome(Myint)
welcome(true);
The above statements will provide the below output:
Output:
It is Educa
It is 1
That is true
Therefore, using generics here, we can reuse 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/object.
Now, let us consider an ArrayList.
Code:
ArrayList myList = new ArrayList();
Let us add data of type String, Integer, and Double to the ArrayList object.
Code:
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].
Output:
If you wish to retrieve these values into variables, you will need to typecast them.
Code:
String someStr = (String)myList.get(0);
Integer someInt = (Integer)myList.get(1);
Double someFlt = (Double)myList.get(2);
If you do not typecast, you will be prompted with a compile-time error stating, “Type mismatch: cannot convert from Object to String.”
Output:
You must typecast them to their respective types while retrieving the objects from your ArrayList. How will you know which data type to typecast it? In real-time, your ArrayList will contain thousands of records, and typecasting it to different data types for every individual object will not be an option. You might end up typecast it to the wrong data type. What happens next?
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:
Code:
ArrayList<String> myList = new ArrayList<String>();
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, it will simply throw a compile-time error. Here you have made your ArrayList type-safe by eliminating its chance of adding a different data type other than “String.”
Output:
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.
Code:
String someStr = myList.get(0);
Output:
How do 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 using generic classes and methods, one can also reuse the code per one 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.
- Bounded & multiple bounded types
- Type wildcards
1. Bounded Type
In the 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 the Runnable interface:
Code:
class myGenericClass<T extends Runnable>{}
Now, while creating its object in another class:
Code:
myGenericClass<Thread> myGen = new myGenericClass<Thread>();
The above statement will execute perfectly without any errors. In the 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?
Code:
myGenericClass<Integer> myGen = new myGenericClass<Integer >();
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<T extends Runnable> of the type myGenericClass<T>.”
Output:
- Multiple bounded types: In the case of multiple bounded types, we can bind the parameter data type to more than one type.
Example:
Code:
class myGeneric<T extends Number & Runnable>{}
In this case, you can pass any type which extends the Number class and implements the Runnable interface.
However, when using multiple bounded types, a few things should be noted:
- We cannot extend more than one class at a time.
- We can extend any number of interfaces simultaneously; that is, there is no limit for interfaces.
- The class name should always come first, followed by the interface name; if not, it will result in a compile-time error.
2. Type Wildcards
They are represented by the “?” – question mark symbol. It makes use of two main keywords:
extends (to define upper bound) and super (to define lower bounds).
Example:
Code:
ArrayList<? extends T> al
This ArrayList object “al” will hold any data of type T and all its subclasses.
Code:
ArrayList<? super T> al
This ArrayList object “al” will hold any data of type T and all its superclasses.
Advantages of Generics in Java
Following are the advantages mentioned:
- Flexibility: Generics allows our code to accommodate different data types with the help of generic classes and methods.
- Code Maintenance and Reusability: Due to generic classes and methods, one need not re-write the code in case of a change in requirements later, making the code easier to maintain and reuse.
- 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.
- 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 code’s length and a coder’s effort.
Generics in Java Skills
- To work with Generics, you should be well versed in the basics of Java.
- You should understand how type checking and typecasting work. 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 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 the generics concept is applicable only at compile time but not at run time.
Example:
Code:
ArrayList myList = new ArrayList<Integer>();
ArrayList myList = new ArrayList<Float>();
ArrayList myList = new ArrayList<Double>();
ArrayList myList = new ArrayList<Boolean>();
Here all the above four statements are the same. They will allow adding any type of data to the list object.
Conclusion
Generics make coding easy for a coder. It diminishes the chances of encountering ClassCastException at run time by providing strong type-checking. It eliminates the need for typecasting, which means less code needs to be written. It allows us to develop generic algorithms independent of the data type they are working with.
Recommended Articles
This is a guide to What is Generics in Java? Here we have discussed the skills, scope, working, understanding, and advantages respectively. You can also go through our other suggested articles to learn more –
41 Online Courses | 29 Hands-on Projects | 305+ Hours | Verifiable Certificate of Completion
4.8
View Course
Related Courses