Generics in Java

Generics in Java

The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects.

Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces the java programmer to store specific type of objects.

Advantage of Java Generics

There are mainly 3 advantages of generics. They are as follows:

1) Type-safety : We can hold only a single type of objects in generics. It doesn’t allow to store other objects.

2) Type casting is not required: There is no need to typecast the object.

Before Generics, we need to type cast.

  1. List list = new ArrayList();
  2. list.add(“hello”);
  3. String s = (String) list.get(0);//typecasting

After Generics, we don’t need to typecast the object.

  1. List<String> list = new ArrayList<String>();
  2. list.add(“hello”);
  3. String s = list.get(0);

3) Compile-Time Checking: It is checked at compile time so problem will not occur at runtime. The good programming strategy says it is far better to handle the problem at compile time than runtime.

  1. List<String> list = new ArrayList<String>();
  2. list.add(“hello”);
  3. list.add(32);//Compile Time Error

Syntax to use generic collection

  1. ClassOrInterface<Type>

Example to use Generics in java

  1. ArrayList<String>

 

Full Example of Generics in Java

Here, we are using the ArrayList class, but you can use any collection class such as ArrayList, LinkedList, HashSet, TreeSet, HashMap, Comparator etc.

  1. import java.util.*;
  2. class TestGenerics1{
  3. public static void main(String args[]){
  4. ArrayList<String> list=new ArrayList<String>();
  5. list.add(“rahul”);
  6. list.add(“jai”);
  7. //list.add(32);//compile time error
  8. String s=list.get(1);//type casting is not required
  9. System.out.println(“element is: “+s);
  10. Iterator<String> itr=list.iterator();
  11. while(itr.hasNext()){
  12. System.out.println(itr.next());
  13. }
  14. }
  15. }

Test it Now

Output:element is: jai
       rahul
       jai 

Example of Java Generics using Map

Now we are going to use map elements using generics. Here, we need to pass key and value. Let us understand it by a simple example:

  1. import java.util.*;
  2. class TestGenerics2{
  3. public static void main(String args[]){
  4. Map<Integer,String> map=new HashMap<Integer,String>();
  5. map.put(1,“vijay”);
  6. map.put(4,“umesh”);
  7. map.put(2,“ankit”);
  8. //Now use Map.Entry for Set and Iterator
  9. Set<Map.Entry<Integer,String>> set=map.entrySet();
  10. Iterator<Map.Entry<Integer,String>> itr=set.iterator();
  11. while(itr.hasNext()){
  12. Map.Entry e=itr.next();//no need to typecast
  13. System.out.println(e.getKey()+” “+e.getValue());
  14. }
  15. }}

Test it Now

Output:1 vijay
       2 ankit 
       4 umesh

Generic class

A class that can refer to any type is known as generic class. Here, we are using T type parameter to create the generic class of specific type.

Let’s see the simple example to create and use the generic class.

Creating generic class:

  1. class MyGen<T>{
  2. T obj;
  3. void add(T obj){this.obj=obj;}
  4. T get(){return obj;}
  5. }

The T type indicates that it can refer to any type (like String, Integer, Employee etc.). The type you specify for the class, will be used to store and retrieve the data.

Using generic class:

Let’s see the code to use the generic class.

  1. class TestGenerics3{
  2. public static void main(String args[]){
  3. MyGen<Integer> m=new MyGen<Integer>();
  4. m.add(2);
  5. //m.add(“vivek”);//Compile time error
  6. System.out.println(m.get());
  7. }}
Output:2

Type Parameters

The type parameters naming conventions are important to learn generics thoroughly. The commonly type parameters are as follows:

  1. T – Type
  2. E – Element
  3. K – Key
  4. N – Number
  5. V – Value

Generic Method

Like generic class, we can create generic method that can accept any type of argument.

Let’s see a simple example of java generic method to print array elements. We are using here E to denote the element.

  1. public class TestGenerics4{
  2.    public static < E > void printArray(E[] elements) {
  3.         for ( E element : elements){
  4.             System.out.println(element );
  5.          }
  6.          System.out.println();
  7.     }
  8.     public static void main( String args[] ) {
  9.         Integer[] intArray = { 1020304050 };
  10.         Character[] charArray = { ‘J’‘A’‘V’‘A’‘T’,‘P’,‘O’,‘I’,‘N’,‘T’ };
  11.         System.out.println( “Printing Integer Array” );
  12.         printArray( intArray  );
  13.        System.out.println( “Printing Character Array” );
  14.         printArray( charArray );
  15.     }
  16. }

Test it Now

Output:Printing Integer Array
        10
        20
        30
        40
        50
        Printing Character Array
        J
        A
        V
        A
        T
        P
        O
        I
        N
        T

Wildcard in Java Generics

The ? (question mark) symbol represents wildcard element. It means any type. If we write <? extends Number>, it means any child class of Number e.g. Integer, Float, double etc. Now we can call the method of Number class through any child class object.

Let’s understand it by the example given below:

  1. import java.util.*;
  2. abstract class Shape{
  3. abstract void draw();
  4. }
  5. class Rectangle extends Shape{
  6. void draw(){System.out.println(“drawing rectangle”);}
  7. }
  8. class Circle extends Shape{
  9. void draw(){System.out.println(“drawing circle”);}
  10. }
  11. class GenericTest{
  12. //creating a method that accepts only child class of Shape
  13. public static void drawShapes(List<? extends Shape> lists){
  14. for(Shape s:lists){
  15. s.draw();//calling method of Shape class by child class instance
  16. }
  17. }
  18. public static void main(String args[]){
  19. List<Rectangle> list1=new ArrayList<Rectangle>();
  20. list1.add(new Rectangle());
  21. List<Circle> list2=new ArrayList<Circle>();
  22. list2.add(new Circle());
  23. list2.add(new Circle());
  24. drawShapes(list1);
  25. drawShapes(list2);
  26. }}
drawing rectangle
drawing circle
drawing circle
Next TopicRMI
java for beginners
java for beginners
java for beginners
CodSir //course // books
...

WikiSir

Generics in Java The Java Generics programming is introduced in J2SE 5 to deal with type-safe objects. Before generics, we can store any type of objects in collection i.e. non-generic. Now generics, forces the java programmer to store specific type of objects. Advantage of Java Generics There are mainly 3 advantages of generics. They are as follows: […]

Tags:

....
...