I have a function that should work on int[] and on String[] now i have made the same function with a int parameter and an String parameter however if it has to go this way its a bit copy paste work and doesn’t look very organized is there a way to solve this and put these 4 functions in 2?
static public void print(String s)
{
System.out.println(s);
}
static public void print(int s)
{
System.out.println(s);
}
static public void printArray(String[] s)
{
for (int i=0; i<s.length; i++)
print(s[i]);
}
static public void printArray(int[] s)
{
for (int i=0; i<s.length; i++)
print(s[i]);
}
Thanks
Matthy
With autoboxing / autounboxing, you can do this:
The one drawback is that the argument to
printArraymust be an array of a reference type, but unlike the varargs solution this will work for any reference type.Edit: regarding the varargs solution and @matthy’s question about combining the two methods into one (ie generifying it), you could also do something like this:
However, you still cannot call it on an array of primitives:
Because Java takes
Tto beint[]and will execute thetoStringmethod of the array rather than iterate through the contents. If you call it on an array ofIntegeror other reference type then it will work also.