Java – Generics

Generics:

  • As we know, collection only store objects.
  • Generics introduced in JDK5.
  • Generics are used to specify what type of objects allowed to store into Collection.

Collection without Generics: Allow to store any type of Objects.

Syntax:
            Collection c = new Collection();
            c.add(10);
            c.add(23.45);
            c.add(“java”);

Collection with Generics: Allow only specific type of data Objects.

Syntax:
            Collection<Integer> c = new Collection<Integer>();
            c.add(10);
            c.add(“java”);  // Error :

Collection with Generics that allows any type of object:

Syntax:
            Collection<Object> c = new Collection<Object>();
            c.add(10);
            c.add(“java”); 
            c.add(23.45);
Note: Object is the super class of all classes in Java

If we store information in Object form, we need to downcast the object into corresponding type to perform operations.

For Example,

Collection<Object> c = new Collection<Object>();
c.add(10);

Downcast to Integer:

Integer x = c.get(0);    
Scroll to Top