What are generics in java?
Generics is a term that denotes a set of language features related to the definition and use of generics types and methods.
Java generics programming is introduced in J2SE 5 to deal with type-safe objects. It makes the code stable by detecting the bugs at compile time.
Java generic methods differ from regular data types and methods so before generics we used collections to store any type of object it can be either generics or non-generic objects now generics force the java programmer to store a specific type of object.
Why java generics?
When the data type is not fixed it is integer or float then checked the data type and assigned the current data type.
Code that uses generics has many benefits over non-generic code:
- Stronger type checks at compile time.
A Java compiler applies strong type checking to generic code and issues errors if the code violates type safety. Fixing compile-time errors is easier than fixing runtime errors, which can be difficult to find.
Elimination of casts.
The following code snippet without generics requires casting:
List list = new ArrayList(); list.add("hello"); String s = (String) list.get(0);
When re-written to use generics, the code does not require casting:
List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); // no cast
- Enabling programmers to implement generic algorithms.
By using generics, programmers can implement generic algorithms that work on collections of different types, can be customized, and are type-safe and easier to read.
Type Parameters
The type parameters naming conventions are important to learn generics thoroughly. The common type parameters are as follows:
- T – Type
- E – Element
- K – Key
- N – Number
- V – Value
Type of java generics:-
- Generic type class
- Generic Method
- Generic Interface
- Generic Constructor
- Generics type class:-
A class is said generics if it declares one or more types of a variable so this variable is known as a parameter of the java class.
Let’s see a simple example to create and use the generic class.
Ex:-
Class GenericClass{ Private object x; Public void set(object x) { this.x = x;} Public object get() { return x; } }
Let’s another example:-
class MyGen<T>{ T obj; void add(T obj){this.obj=obj;} T get(){return obj;} }
The T type indicates that it can refer to any type (like String, Integer, and Employee). The type you specify for the class will be used to store and retrieve the data.
- Generic Method:-
We can write a single generic method declaration that can be called with arguments of different types.
EX:-
Public class Example{ Public <E> void printArrayElement( E a[]){ for(E x : a ){ System.out. println(“ ” + x); } } public static void main( String[] args) { Example e1=new Example(); String s[]= new String[]; {“India”,”Pakistan”,”Nepal”} e1.printArrayElement(s); }
IMPORTANT POINT:-
All generic method declarations have a type parameter section delimited by angle brackets (<>) that precedence the method’s return type.
- Each type of parameter section contains one or more type parameters separated by commas.
- The type parameters can be used to declare the return type.
- Type parameter can represent only reference type not primitive type (like int, double, and char)
- Generic Interface:-
Generics also work with interfaces. Thus, you can also have generic interfaces. Generic interfaces are specified just like generic classes. For example : interface MyInterface<T> ( void myMethod (T t); —-------->Generic Interface } class Myclass implements MyInterface<Integer> { public void myMethod (Integer 1) { System.out.println("MyMethod -> 1-> "+1); }
The MyInterface is a generic interface that declares the method called myMethod( ). In general, a generic interface is declared in the same way as a generic class. In this case, the type parameter is T. Next, MyClass implements MyInterface. Myclass is a non-generic class. Of course, if a class implements a specific type of generic interface, then the implementing class does not need to be generic.
We can create generic interfaces in java. We can also have multiple types of parameters as in the map interface. Again we can provide parameterized value to a parameterized type also.
For Example:-
New HashMap<String, List<String >>(); is valid.
- Generic Constructor:-
Generic constructors are the same as generic methods. For generic constructors after the public keyword and before the class name the type parameter must be placed. Constructors can be invoked with any type of parameter after defining a generic constructor. A constructor is a block of code that initializes the newly created object. It is an instance method with no return type. The name of the constructor is the same as the class name. Constructors can be Generic, despite their class is not Generic.
Example:-// Java Program to illustrate Generic constructors
import java.io.*; class GenericConstructor { private double v; <T extends Number> GenericConstructor(T t) { v = t.doubleValue(); } void show() { System.out.println("v: " + v); } } class Main { public static void main(String[] args) { System.out.println("Number to Double Conversion:"); GenericConstructor obj1 = new GenericConstructor(10); GenericConstructor obj2 = new GenericConstructor(136.8F); obj1.show(); obj2.show(); } }
Output:-
Number to Double Conversion:
v: 10.0
v: 136.8000030517578