Have a look at how the equivalent function Arrays.toString()
(JavaDoc) is implemented. It's one function that will take an Object[]
for example an Integer[]
, and one for each kind of primitive-array like int[]
. Here's the code for the Object[]
and the int[]
version:
Object[]:
public static String toString(Object[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(String.valueOf(a[i]));
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
int[]:
public static String toString(int[] a) {
if (a == null)
return "null";
int iMax = a.length - 1;
if (iMax == -1)
return "[]";
StringBuilder b = new StringBuilder();
b.append('[');
for (int i = 0; ; i++) {
b.append(a[i]);
if (i == iMax)
return b.append(']').toString();
b.append(", ");
}
}
There's a lot to learn from this code. For example it's not using Generics in any way.
If you actually wanted to make a method that could take any array it would probably have to take an Object
, which you could then check the class of, and invoke the appropriate Arrays.toString()
(or generate a string manually). Probably not a good idea, however. We have overloading for a reason.
Edit:
Just for fun, here is such a method that will take any array. Actually, any Object at all.
public static void printAny(Object arr) {
Class<?> cl = arr.getClass();
if (cl.isArray()) {
Class<?> type = cl.getComponentType();
if (!type.isPrimitive()) {
System.out.println(Arrays.toString((Object[]) arr));
} else {
switch (type.toString()) {
case "int":
System.out.println(Arrays.toString((int[]) arr));
break;
}
}
} else {
System.out.println(arr);
}
}