简体   繁体   中英

sending array as parameter in java generic method

class MaximumTest {
    // determines the largest of three Comparable objects
    public static <T extends Comparable<T>> int CountDuplicates(T[] anArray, T elem) {
        int count = 0;
        for (T e: anArray)
            if (e.compareTo(elem) == 0)
            ++count;
        return count;
    }
    public static void main(String args[]) {
        double[] D_arr = {
            1.2, 3.4, 0.0, 4.5, 0.0
        };
        int[] I_arr = {
            0, 0, 0, 0, 1, 3, 5
        };
        System.out.println("No of zeros in Double Array = " + CountDuplicates(D_arr, 0.0));
        System.out.println("No of zeros in Double Array = " + CountDuplicates(I_arr, 0));
    }
}

What is the mistake in this code??

Your arrays should be of reference type:

Double[] D_arr = {1.2, 3.4, 0.0, 4.5, 0.0};
Integer[] I_arr = {0,0,0,0,1,3,5};

A primitive type cannot be used as a generic type.

After this change, your code will pass compilation and produce the output:

No of zeros in Double Array = 2
No of zeros in Double Array = 4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM