I'm working on a project that requires me to have a string representation of an array. The problem is having this duplicated code, that I'm sure can be refactored in some way, but I haven't found one yet.
private static String printDoubleArray(String title, double[] array){
String result = title;
for (double d : array) {
result += d + " ";
}
return result;
}
private static String printIntArray(String title, int[] array){
String result = title;
for (int d : array) {
result += d + " ";
}
return result;
}
Thanks in advance.
You can use java.lang.reflect.Array
that allows access to elements of any time of array. See get(arr, index)
, getLength(arr)
etc.
Why not use one of the methods Arrays.toString(...)
from java.util
package?
int[] intArray = {1, 2, 4};
double[] doubleArray = {1.1, 2.2, 4.4};
System.out.println(Arrays.toString(intArray));
System.out.println(Arrays.toString(doubleArray));
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