Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: Java
Expertise: Intermediate
Feb 24, 2004



Building the Right Environment to Support AI, Machine Learning and Deep Learning

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()) {
            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);

Amit Vij
Thanks for your registration, follow us on our social networks to keep up-to-date