Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect if an array contains integer or double

Tags:

java

numbers

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.

like image 893
Roberto Luis Bisbé Avatar asked Aug 25 '11 06:08

Roberto Luis Bisbé


2 Answers

You can use java.lang.reflect.Array that allows access to elements of any time of array. See get(arr, index), getLength(arr) etc.

like image 180
AlexR Avatar answered Oct 11 '22 15:10

AlexR


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));
like image 29
True Soft Avatar answered Oct 11 '22 15:10

True Soft