Tuesday, 16 April 2019

Generic in Java | Example of Generic in android | Generic method | Generic Class in android or java

What is Generic:-
Ans:- Generic are used to check the type compatibility at the compile time. It will reduce the chances of ClassCastException at run time.

Generic Class example:-
class GenericClass<T> {

    T x;

    //setter    public void setX(T t) {
       this.x = t;
    }
    //getter    public  T getX(){
        return x;
    }
}
Generic Method:-

//Array in genericpublic static <E> void printArray(E[] array) {
    for (E element : array) {
        Log.d("supriya", element + "");
    }
}


// find max using comparable in Genericprivate static <T extends Comparable<T>> T maximum(T x, T y, T z) {
    T max = x;
    if (y.compareTo(max) > 0) {
        max = y;
    }
    if (z.compareTo(max) > 0) {
        max = z;
    }
    return max;
}


//addition in Genericprivate <T> T add(T a, T b) {
    Integer result = (Integer) a + (Integer) b;
    Log.d("Supriya Add==  ", result + "");
    return (T) result;
}

//a method can hold both generic and non generic dataprivate <T> void setUserData(GenericClass<T> genericClass, String name) {
    genericClass.setX((T) "supriya");
    Log.d("supriya", "Name ::= "+name + "\n"+"generic data :: "+genericClass.getX());

}

Calling of method are following :- 

printArray(number);
printArray(str);
int max = maximum(120, 34, 79);
Log.d("AndroidHubb" + " Maximum = ", max + "");
int value = add(12, 13);
Log.d("supriya" + " Add2:;  = ", value + "");

GenericClass genericClass = new GenericClass();
genericClass.setX(20);
Log.d("AndroidHubb", "genericClass :: " + genericClass.getX());
setUserData(genericClass,"Generic");

No comments:

Post a Comment