Monday, 20 February 2017

What is Generic? Explain with example?

Generics are used for compile type safety.
Compile with warning doesn’t matter but when we are using generics and mixing typed and untyped code, warning matters.

What is the difference between arrays and generic?
Arrays provide both runtime and compile time protection while generic provide only compile time protection at runtime there is no type information this is to support legacy code.
Compile time protection also provide unnecessary type safety casting.


Explanation with example-

Below code snippet list of type String
List<String> list = new ArrayList<String> ();
Above code more optimized in java7
List<String> list = new ArrayList<> ();



Important point-

Polymorphism doesn’t work the same ways as it works for other object.
Like Integer is a subtype of Number but we represent generic like this-
               List<Number> number = new ArrayList<Integer>();

Above line will give compile time error - Type mismatch: cannot convert from ArrayList<Integer> to List<Number>

Although we can add child type object in a list of parent type.

List<? Extends Animal> - anything that extends Animal.
List<? Super Dog> - Dog or super type of Dog.


Generics can’t be applied on Enums

No comments:

Post a Comment