简体   繁体   中英

How to get the length of any dimension of multidimensional array in Java?

Is there any ready implementations in JDK or popular libraries?

I wrote the following function:

public static int length(Object array, int level) {
        if( level < 0 ) {
            throw new IllegalArgumentException();
        }
        else if( level == 0 ) {
            if( !array.getClass().isArray() ) {
                throw new IndexOutOfBoundsException();
            }
            else {
                return Array.getLength(array);
            }
        }
        else {
            if( !array.getClass().isArray() ) {
                throw new IndexOutOfBoundsException();
            }
            else {

                int length = Array.getLength(array);
                int nextlength, maxnextlength = 0;
                Object element;
                for(int i=0; i<length; ++i) {
                    element = Array.get(array, i);
                    if( element != null ) {
                        nextlength = Array.getLength(element);
                        if( nextlength > maxnextlength ) {
                            maxnextlength = nextlength;
                        }
                    }
                }
                return maxnextlength;
            }
        }
    }

is it correct and optimal?

Take a look on java.util.Arrays and java.lang.reflect.Array . They have functions that can help you. At least your method may be shorten.

  1. It is a very costly operation... are you sure you cannot avoid it? You are implying that you will scan the entire multi-dimensional array upto the depth that you want the length!
  2. It looks like a recursive algorithm will be best suited for this
  3. If you want to make it recursive, think about breadth-first or depth-first (if level is more than 2) (this will only help to give clarity for writing... this is not going to help in optimization as there is not much room for optimization)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM