Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parameter For All Primitive Types of Java?

I have this function;

static public void Print(Object[] arr) {
    for(int i = 0; i < arr.length; i++)
        System.out.println(i + " => " + arr[i]);
}

I want to use that for every primitive type array. Isn't there any way to do that without overriding it for every primitive type?

Note: This is just an example function. I want to know the technique if there is one.

like image 645
previous_developer Avatar asked Mar 29 '26 17:03

previous_developer


2 Answers

No, this is not possible. Array element types are not wrapped, Object[] formal parameter is not applicable for e.g. int[] actual parameter. You have to write one method per primitive type, as in java.util.Arrays. Ugly, but the only way.

like image 164
Hauke Ingmar Schmidt Avatar answered Mar 31 '26 09:03

Hauke Ingmar Schmidt


Primitive arrays are Objects in java, so you could use Object-type as the parameter (note, not an array of Objects, but just Object). The problem is, you'd still need to cast it to correct type to be able to iterate the array.

public class ArrayTest
{
    public void paramTest(Object args)
    {       
        if(args instanceof int[])
        {
            System.out.println("int-array");
        }

        if(args instanceof float[])
        {
            System.out.println("float-array");
        }
    }

    @Test
    public void test()
    {
        paramTest(new int[5]);
        paramTest(new float[5]);
    }
}

Output:

int-array
float-array
like image 45
esaj Avatar answered Mar 31 '26 10:03

esaj



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!