What are the advantage of generics?

Generics was introduced in JAVA 5 version.
It has the following advantages

  1. 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 run-time errors, which can be difficult to find.                                                                                                                                         
  2. Elimination of casting:-
    The following code snippet requires casting due to absence of  generics
    List list = new ArrayList();
    list.add("hello");
    String s = (String) list.get(0);//type casting
    
    with generics, the code does not require type casting
    List<String> list = new ArrayList<String>();
    list.add("hello");
    String s = list.get(0);   // no need of casting                        
  3. Enabling programmer to implement generic algorithm:-
         Which can be
         Generic CLASS declaration
         Generic INTERFACE declaration
         Generic METHOD declaration
         Generic CONSTRUCTOR declaration

No comments:

Post a Comment