A Few Functions in a Java's Generic Class

Here are the three functions that I didn't include in my earlier post.  The constructor function is revised, and variable T[] sortedNumArray is added.  All those can be plugged into the GenericNumberStat class.

    T[] numArray;
    T[] sortedNumArray;

    GenericArrayStat (T[] numArray) {
        this.numArray = numArray;
        T[] tmpArray = numArray.clone();
        Arrays.sort (tmpArray);
        this.sortedNumArray = tmpArray;
    }
    
    Double median () {        
        int len = sortedNumArray.length;
        double med;                
        if (len % 2 == 0) {
            double sumOfMidNums = sortedNumArray[len/2].doubleValue() + sortedNumArray[len/2 - 1].doubleValue();        
            med = sumOfMidNums / 2;
        } 
        else {        
            med = sortedNumArray[len/2].doubleValue();
        }        
        return med;        
    }    
    
    T minimum () {                
        return sortedNumArray[0];
    }    
    
    T maximum () {
        int len = sortedNumArray.length;
        return sortedNumArray[len-1];
    }    

The class constructor
The design of this constructor function is to take in the original unsorted array, memorize it by variable T[] numArray; also, memorize the sorted array by variable T[] sortedNumArray.  It is convenient to have both the original and sorted sequence handy.  They serve different purposes when more functions need to be added to the Class.  

The median() function
Like the mean() function provided previously, the median() function returns a Double object.  It is reasonable to return a Double object because the calculation is based on the primitive double datatype.  Returning a Double object (instead of a primitive double) is often more convenient due to the functions available in the Double class.

The minimum() and maximum() functions
Unlike the mean() and median() functions, the minimum() and maximum() functions return a generic T object.  This is because the minimum() and maximum() functions do not need to calculate; they simply return the lowest or highest element respectively.

Note that in the class constructor, there is the usage of Arrays.sort(x) function.  Before using the sort function in the Arrays class, import java.util.Arrays; otherwise, the compiler won't recognize it.  According to the official Java Doc, this sort function is implemented based on "a stable, adaptive, iterative mergesort that requires far fewer than n lg (n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered."

Comments

Popular posts from this blog

Finding Median by Stream

Factorial by Different Styles in Java

Reduction by Java Stream