Generics solves 2 problems –
  • Type casting
  • Type safety
Explanation – Normal ArrayList class is not generic. We can store any type of object in same ArrayList which causes type casting and type safety problems. ArrayList a = new ArrayList(); But In Generic ArrayList, we can store only specific types. For example, in below ArrayList instance, we can only store String objects.
 
ArrayList<String> a = new ArrayList<>();
 
ArrayList<String> a = new ArrayList<>();
package generics;

/**
 * Created by ssalunke on 15/04/2016.
 */

/*
Without Generics, we will have to create 2 different Classes
each working with specific Type say Water and Petrol. Here note 
that <G> is a type of Parameter.
*/

public class MyGenericClass <G> {

    G liquid;
    public static void main(String [] args){
        MyGenericClass<Water> w = new MyGenericClass<>();
        w.liquid = new Water();

        MyGenericClass<Petrol> p = new MyGenericClass<>();
        p.liquid = new Petrol();

    }
}


class Water{
}

class Petrol{
}

Bounded Types in Generics

Bounded types allow us to restrict the types to specific set of classes. For example – Mathematical operations can be performed only on Classes inherited by Number class. So we can restrict the types using extends keyword. In below example, we can create instance of BoundedTypes class using only Number Type or it’s child classes.
 
package generics;

/**
 * Created by ssalunke on 15/04/2016.
 */

//Bounded types are required when we need to work with specific types only
//For example - if we have a generic class that does mathematical operations
//then we should restrict the types using Bounded types
public class BoundedTypes <T extends Number>{

    public void add(T a, T b){
        System.out.println("Sum of numbers is " + (a.doubleValue()+b.doubleValue()));
    }

    public void multiply(T a, T b){
        System.out.println("Multiplication of numbers is " + (a.doubleValue()*b.doubleValue()));
    }

    public static void main(String [] args){

        BoundedTypes<Integer> intTypes = new BoundedTypes<>();
        intTypes.add(11,22);
        intTypes.multiply(11,22);

        BoundedTypes<Float> floatTypes = new BoundedTypes<>();
        floatTypes.add(32.2f,22.4f);

        BoundedTypes<Double> doubleTypes = new BoundedTypes<>();
        doubleTypes.add(132.2d,222.4d);

    }
}
Here is the output of above example.

Sum of numbers is 33.0
Multiplication of numbers is 242.0
Sum of numbers is 54.60000038146973
Sum of numbers is 354.6

Web development and Automation testing

solutions delivered!!