Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic method to fill an array

I'm learning java for school and the subject is generic methods. I need to write an application that has a generic method to "fill" an array of any type with the same element. but its not working... can anyone help me :

package pack.switchshift;
import java.lang.reflect.Array;

public class Filler {

    public static void main(String [] args) {
        int[] intArr = new int[10];
        String[] stringArr = new String[10];
        double[] doubleArr = new double[10];

        genFill(intArr, 0);
        genFill(stringArr, "0");
        genFill(doubleArr, 0.0);

        for (int element : intArr){
            System.out.print(element);
        }
    }

    private static <T> void genFill(T[] arr, T element) {
        for (int i = 0; i < arr.length; i++) {
            arr[i] = element;
        }
    }
}

I tried multiple approaches at this and spent some hours researching, but I'm still not getting it.

Exception in thread "main" java.lang.Error: Unresolved compilation problems:
The method genFill(T[], T) in the type Filler is not applicable for the arguments (int[], int)
The method genFill(T[], T) in the type Filler is not applicable for the arguments (double[], double) at pack.switchshift.Filler.main(Filler.java:11)

like image 345
Synbitz Prowduczions Avatar asked May 15 '26 16:05

Synbitz Prowduczions


1 Answers

Generics doesn't always work for primitive types (I wrote always because you can pass a primitive int type to a parameter of type T. In which int will auto-boxed to Integer). You can't create an ArrayList<int>, similarly you can't pass an int[] or any other primitive type array where a T[] array is expected. You have to pass an Integer[] instead. Similarly pass Double[] instead of double[].

Think of it this way, the generic method is compiled to a type erased method by the compiler. In that process, the type parameter T here is erased to it's left-most bound Object. So, your method after compilation is equivalent to:

private static void genFill(Object[] arr, Object element)

Now, you can understand you can't pass an int[] where an Object[] is needed.

like image 121
Rohit Jain Avatar answered May 17 '26 08:05

Rohit Jain



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!