Advance Java

Learn New things from Rixosys

What is Java Generics ?

Java Generics 

1. Objective

In this Java Generics tutorial, we are going to study what is Java Generics and Java Generic Class with multiple parameters. Moreover, we will study the various advantages and Functions of generics in Java. At last, we will how to use generics in java with example.

So, let us start what is generics in Java with simple example.

What is Generics in Java?

Generics is introduced in the JDK version 5.0 and it is a facility for generic programming in the Java programming language. With the help of Generics in Java you can define a type or method to an object of various, which will be used for compile-time safety checking. Philip Wadler created Generic Java in the year 1998.

Following is simple example of Generics in Java:

List<String> list = new ArrayList<String>();
list .add("Hello");
Integer i = list .get(0); // (type error) Compile time error

In the above code we have used the Generics <String> while defining the array list. The type of to be stored in the array list is just the String. If we try to type cast the data into Integer it will give compile time error. So, this way compiler will be able to find our the error at the compile time in your program and remove the errors related to invalid types.

Why use Generics in Java program?

The Generics is introduced for the compile time checking of the types, so you can now use Generics in your Java make it more bug free. The compile time checking helps the programmers to find out the bugs at the development time and remove it from the code.

Generics allows the developers to use the types (classes/interfaces) while defining classes, interfaces and methods in your Java program. This is much like defining the formal parameters used while defining methods. This will enable the code to just accept the values of defined type only and it is checked at compile time.

Here are the benefits of using the Generics over the non-generic Java codes:

  • Stronger type checking: The Generics type checking are performed at the compile time and it reports if there is some violation of the types. So, your program are now more bug free.
     
  • Elimination of cast in the program: If you use the Generics in your program there is no need to cast to particular type in your code. For example in the above code we have define it as String type for the list and we don't have to cat it to String. We can simple write the code String s = list .get(0);
      
  • Use of generic algorithms: By using the Generics in your code you can use the generic algorithms that works with collections and other types. You will also make your code type safe and error free.

2. What is Java Generics?

Generics in Java is like templates in C++. The thought is to permit write (Integer, String and so on and user-defined types) to be a parameter to techniques, classes, and interfaces. For instance, classes like HashSet, ArrayList, HashMap, and so forth utilize generics exceptionally well. We can utilize them for any kind.

a. What is Java Generic Class?

<> is used to specify parameter types in Java generic class creation.
The syntax for creating a Java generic class–

           BaseType <Type> obj = new BaseType <Type>()

Note: In Parameter type, we cannot use primitives like ‘int’,’char’ or ‘double’.
Example –

class Test<T>
{
// An object of type T is declared
T obj;
Test(T obj)
{ this.obj = obj; } // constructor
public T getObject() { return this.obj; }
}
class Main
{
public static void main (String[] args)
{
Test <Integer> iObj = new Test<Integer>(15);
System.out.println(iObj.getObject());
Test <String> sObj =
new Test<String>("DataFlair");
System.out.println(sObj.getObject());
}
}

b. Multiple type Parameters in Generic Classes in Java

class Test<T, U>
{
T obj1; // An object of type T
U obj2; // An object of type U
// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}
// To print objects of T and U
public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}
class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj =
new Test<String, Integer>("GfG", 15);
obj.print();
}
}

3. Java Generic Functions

We can also write generic functions in Java as they can be called by generic arguments which are handled by the compiler in Java.

Example –

class Test
{
static <T> void genericDisplay (T element)
{
System.out.println(element.getClass().getName() + " = " + element);
}
public static void main(String[] args)
{
genericDisplay(11);
genericDisplay("datflair");
genericDisplay(1.0);
}
}

4. Advantages of Java Generics

Projects that utilizations Java Generics has numerous advantages over the non-generic code.

i. Code Reuse  :-  We can compose a strategy/class/interface once and use for any kind we need.
 

ii. Sort Safety  :-  Java Generics influence mistakes to seem to order time than at runtime (It’s constantly better to know issues in your code at an aggregate time as opposed to influencing your code to fall flat at run-time). Assume you need to make an ArrayList that store name of understudies and if by botch software engineer includes a whole number question as opposed to string, compiler permits it. However, when we recover this information from ArrayList, it causes issues at runtime.

import java.util.*;
class Test
{
public static void main(String[] args)
{
// Creatinga an ArrayList without any type specified
ArrayList al = new ArrayList();
al.add("Sachin");
al.add("Rahul");
al.add(10);
String s1 = (String)al.get(0);
String s2 = (String)al.get(1);
String s3 = (String)al.get(2);
}
}

iii. Individual Type Casting isn’t required

If we don’t utilize Java generics, at that point, in the above case each time we recover information from ArrayList, we need to typecast it. Typecasting at each recovery task is a major migraine. On the off chance that we definitely realize that our rundown just holds string information then we require not to pigeonhole it each time.

class Test
{
public static void main(String[] args)
{
// Creating a an ArrayList with String specified
ArrayList <String> al = new ArrayList<String> ();
al.add("Sachin");
al.add("Rahul");
// Typecasting is not needed
String s1 = al.get(0);
String s2 = al.get(1);
}
}

iv. Implementing nongeneric algorithms

By utilizing generics in Java, we can actualize calculations that work on various sorts of items and at a similar, they are type safe as well.

Generics Naming conventions

The Generics in Java follows some notations and the naming convention. The main problem of using the Generics is that the developers is not aware of the naming conventions of the Generics. After familiarizing these naming conventions and the notations you will find it very easy. Here is the naming conventions followed in the Java Generics:

Generic Term Meaning
Set<E> This is the Generic Type and here E is called formal parameter
Set<Integer> This is Parameterized type and Integer is actual parameter here
<T extends Comparable> This is bounded type parameter in Generics
<T super Comparable> This is bounded type parameter in Generics
Set<?> This is Unbounded wildcard in Generics
<? extends T> This is Bounded wildcard type in Generics
<? Super T> This is Bounded wildcards type in Generics
Set This is Raw type
<T extends Comparable<T>> This is Recursive type bound in the Generics

Conventions:

T - Is used to denote type
E - Is used to denote element
K - Is keys
V - Is the values
N - Is used for the numbers