Monthly Archives: April 2017

Generics in Java


  • Introduced in JDK 1.5
  • Provide compile-time type safety
  • Enable developer to declare generic class or method

Some problems solved by Generics

Problem 1 – No compile-time safety

List list = new ArrayList();
Integer i = (Integer)list.get(0); // throws run time ClassCastException
  • Generics provides compile-time safety and avoid run time errors like above
List<String> list = new ArrayList<>();
// compile-time error Cannot cast from String to Integer
Integer i = (Integer) list.get(0);