Generics in Java allows you to create classes and objects that can deal with any defined types. Programmers use the Generics feature to make his code better. Generics programming makes Classes and Methods to operate on well defined parametric types allowing clients to substitute a suitable Java type at the compile time. It prevents the un-necessary casting being done in the Application code and to prevent any wrong data-type being used.
Generic types are mostly used in Java collections. Finding bugs in compile-time saves time for debugging java program, because compile-time bugs are easier to find and fix. Generic are used to find bugs at compile time.
What´ll happen if there is no Generics?
-----------------------------------------------------
In the following code, the ?Room? class defines a member object. We may pass any object to it, such as Integer, String etc.
class Room {
private Object object;
public void add(Object object) {
this.object = object;
}
public Object get() {
return object;
}
}
public class Main {
public static void main(String[] args) {
Room room = new Room();
room.add(60);
//room.add("60"); //this will cause a run-time error
Integer i = (Integer)room.get();
System.out.println(i);
}
}
The above program runs totally fine when we add an integer and cast it. But anyhow if a user accidentally add a string "60" to it, compiler does not understand that it is a problem. When the program is run, it will throw a ClassCastException.
Exception in thread "main" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Integer at collection.Main.main(Main.java:21)
You may think why not just declare the field type to be Integer instead of Object. If so, then the class room is not so much flexible because it can only store one type of thing.
When generics is used:
----------------------------------------
If generics is used here, the program becomes like the following.
class Room<T> {
private T t;
public void add(T t) {
this.t = t;
}
public T get() {
return t;
}
}
public class Main {
public static void main(String[] args) {
Room<Integer> room = new Room<Integer>();
room.add(60);
Integer i = room.get();
System.out.println(i);
}
}
Now if someone adds room.add("60"), It will show an error at compile time. This time compiler knows that which kinf of values should be added. In addition, there is no need to cast the result from room.get() since compile knows get() will return an Integer.
Where T refers simply Type...
5