Sunday, December 8, 2019

What is the benefits of generic in java?

Problem statement: List out the benefits of generic in java.
  1. type safety
  2. type erasure
  • type safety: what exactly mean of type safety, Compiler guarantee that if correct types are used in correct places means within angular braces then there should not be any ClassCastException in runtime. A use case can be a list of Integer i.e. List<Integer>.If we declare a list in java like List<Integer>, then java guarantees that it will detect and report us any attempt to insert any non-integer type into above list.
  • type erasure: what exactly mean of type erasure, It essentially means that all the extra information added using generics into sourcecode will be removed from bytecode generated from it. Inside bytecode, it will be old java syntax which you will get if you don’t use generics at all. This necessarily helps in generating and executing code written prior java 5 when generics were not added in language.
Let’s understand with an example.

List<Integer> list = new ArrayList<Integer>(); 
list.add(1000);     //works fine 
list.add("lokesh"); //compile time error 

When we write above code and compile it, we will get an error: “The method add(Integer) in the type List<Integer> is not applicable for the arguments (String)“. Compiler warned us. This is what exactly generics sole purpose i.e. Type Safety.

Second part is getting bytecode after removing second line from above example. If you compare the bytecode of above example with/without generics, then there will not be any difference. Clearly compiler removed all generics information. So, above code is very much similar to below code without generics.

List list = new ArrayList(); 
list.add(1000);

No comments:

Post a Comment

How to run standalone mock server on local laptop

 Please download the standalone wiremock server from Direct download section at the bottom of the page.  Download and installation Feel fre...