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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With