Function to determine if an array is one-dimensional

In Java, how can I write a function like the following to determine if an array is one-dimensional? (The compiler refuses to compile this because of the part array[i].lengthsince it was arraynot declared as a nested array.)

boolean isOneDimensional(Object[] array)
{
    for (int i=0; i<array.length; i++)
        if (array[i].length>1) return false;
    return true;
}
+4
source share
1 answer

You get Classto write through getClassand set this class if it is an array type through isArray:

boolean isOneDimensional(Object[] array)
{
    // Assuming you want an NPE if `array` is `null`, so not checking
    for (int i=0; i<array.length; i++)
        if (array[i] != null && array[i].getClass().isArray()) return false;
    return true;
}

Pay attention to the check nulljust in case.

No, my bad one, the above gives the wrong result:

isOneDimensional(new String[2][])

, , , : , Object[], , , , - Object[], , new String[2][].

, ; , array.getClass().getComponentType().getComponentType():

boolean isOneDimensional(Object[] array) {
    // Assuming you want an NPE if `array` is `null`, so not checking
    if (array.getClass().getComponentType().getComponentType() != null) {
        return false;
    }
    for (int i=0; i<array.length; i++) {
        if (array[i] != null && array[i].getClass().isArray()) {
            return false;
        }
    }
    return true;
}

, getComponentType null, , Object[], . , , .

String[]   o1 = new String[2];      // Yes, it one-dimensional
String[][] o2 = new String[2][];    // No, it isn't
Object[]   o3 = new Object[2];      // It may or may not be, depending on contents
Object[]   o4 = new Object[2];      // It may or may not be, depending on contents

// This makes `o3` multi-dimensional
o3[0] = new Object[0];
System.out.println(isOneDimensional(o1));   // true
System.out.println(isOneDimensional(o2));   // false
System.out.println(isOneDimensional(o3));   // false
System.out.println(isOneDimensional(o4));   // true
+4

Source: https://habr.com/ru/post/1653564/


All Articles