devxlogo

Getting the Length and Dimensions of an Array Object

Getting the Length and Dimensions of an Array Object

A given array of objects can be one-dimensional, two-dimensional, three-dimensional, or n-dimensional. How can you tell? In this tip, the function getDim(Object o) takes an object and finds out it’s dimension. The length is calculated from an in-built static method Array.getLength(o).

There are instances when you need to represent an n-dimensional array to a linear array. That’s when you actually need to find out the dimension and length of an array so as to derive at a generic formula for conversion. Conversion in a “SPARSE MATRIX” is a typical example.

Here’s the code:

import java.lang.reflect.*;public class Reflec{    public static int getDim(Object array) {        int dim = 0;        Class cls = array.getClass();        while (cls.isArray()) {            dim++;            cls = cls.getComponentType();        }        return dim;    }  public static void main(String[] args){    Object o = new int[1][2][3];    // Get length    int len = Array.getLength(o);  //Will Output 1    // Get dimension    int dim = getDim(o);  //Will Output  3    System.out.println("Len : " + len + ", Dim : " + dim);  }}
See also  Professionalism Starts in Your Inbox: Keys to Presenting Your Best Self in Email
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist