An Example of Java Generics


Generics is a useful feature in the Java language (and other contemporary languages).

Generics lets us build classes or functions without defining specific data type(s).  That allows those coding blocks to be more reusable, and bugs to be more detectable at compile time.  There are many ways to incorporate Generics in code.  Below is a practical example.

The GenericNumberStat class will accept an array of Object T.  What is T?  In this example, T is a Number. That means an array of any one of the sub-classes of Number can be passed to the constructor of this class.

When we create a function, the traditional way requires us to define the specific parameter type(s).  With Generics, we don't need to define the specific types in the function. We define them when we instantiate an object.

I provided with the mean() function to show how to use the generic array.  (To keep the code concise, I haven't included median(), minimum() and maximum() in this example.)


class GenericNumberStat <T extends Number> {

    T[] numArray;

    GenericNumberStat (T[] numArray) {
        this.numArray = numArray;
    }

    Double mean() {
        double sum = 0d;
        for (T num : numArray) sum += num.doubleValue();
        return sum / numArray.length;
    }

    /*    
    Double median () {}
    T minimum () {}    
    T maximum () {}
    */    
}

class GenericNumberArrayExample {

    public static void main (String args[]) {

        Integer[] iNumArray = {5, 4, 5, 6, 8, 9, 9, 10, 9, 9, 6, 5};
        GenericNumberStat <Integer> numHousesSold = new GenericNumberStat <> (iNumArray);
        
        System.out.println ("For the number of houses sold: ");
        System.out.println ("Mean = " + numHousesSold.mean()) ;
        
        Double[] dNumArray = {1120000d, 780000d, 890000d, 910000d, 1210000d};
        GenericNumberStat <Double> soldPrices = new GenericNumberStat <Double> (dNumArray);
        
        System.out.println ("For the sold prices in the first month: ");
        System.out.println ("Mean = " + soldPrices.mean());        
    }
}

The above program produces this result:

For the number of houses sold:
Mean = 7.083333333333333
For the sold prices in the first month:
Mean = 982000.0


Comments

Popular posts from this blog

Finding Median by Stream

Factorial by Different Styles in Java

Reduction by Java Stream