Generics in Java

Generics

  • 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();
list.add("oneness");
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<>();
list.add("oneness");
// compile-time error Cannot cast from String to Integer
Integer i = (Integer) list.get(0);

Leave a Reply

Your email address will not be published. Required fields are marked *