Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.

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
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.



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