How can you write a function that accepts multiple types?
Solution 1
With autoboxing / autounboxing, you can do this:
public static void print(Object s) {
System.out.println(s.toString());
}
public static <T> void printArray(T[] arr) {
for (T t : arr) {
print(t);
}
}
The one drawback is that the argument to printArray
must 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:
static public <T> void print(T... ts) {
for (T t : ts) {
System.out.print(t + " ");
}
System.out.println("");
}
However, you still cannot call it on an array of primitives:
int[] x = { 1, 2 };
print(x);
Because Java takes T
to be int[]
and will execute the toString
method of the array rather than iterate through the contents. If you call it on an array of Integer
or other reference type then it will work also.
Solution 2
static public void print(String...strings){
for(String str : strings){
System.out.println(str);
}
}
static public void print(int...ints){
for(int i : ints){
System.out.println(i);
}
}
Solution 3
Well, the Basic class java.lang.Object matches String as well as int, byte, ... (Autoboxing converts them to Integer, Byte and so on). The method String.valueOf()
lets you create a string of these. (toString() is available too)
matthy
Updated on June 15, 2022Comments
-
matthy almost 2 years
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
-
matthy almost 14 yearsi meanth the oposite like what danben said but this looks interesting too is it possible to combine these 2 method's so you have only one function?
-
user102008 over 12 yearsGenerics adds nothing here. It is equivalent to
public static void printArray(Object[] arr) { for (Object t : arr) { print(t); } }
-
user102008 over 12 yearsgenerics adds nothing here. it is the same as
static void printArray(Object[] s)
-
AncientSwordRage almost 11 yearsTry
ts.tostring.split(",")
which guarantees parsing of primitives, doesn't it? -
GhostCat almost 7 yearsThe question is not to simply use different types in one method. This is really not at all an answer to the question!