Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the type of array element in Java

I have the following method:

public static int arraySum(Object obj) {
}

The method should return the sum of all elements in obj; a precondition for this method is that obj be an Integer array of any dimension, i.e. Integer, Integer[], Integer[][], so on.

In order to write the body of the method arraySum(), I'm using a foreach loop and recursion; however, for the foreach loop I need to know which type the elements of obj are. Is there a way to find out the type (i.e. Integer, Integer[], etc.) of obj?

EDIT: This is for an assignment for my CS course. I don't want to simply ask how to write the method, that's why I'm asking such a specific question.

like image 583
apparatix Avatar asked May 19 '26 08:05

apparatix


1 Answers

I believe it's simpler than you think:

public static int arraySum(Object obj) {
    if (obj.getClass() == Integer.class)
        return ((Integer) obj).intValue();

    int sum = 0;
    for (Object o : (Object[]) obj)
        sum += arraySum(o);

    return sum;
}

Basically we exploit the fact that an Integer array of any dimension is still an Object[].


Object obj = new Integer[][][]{{{1,2,3}},{{4,5,6},{7,8,9}},{{10}}};

System.out.println(arraySum(obj));
55
like image 156
arshajii Avatar answered May 20 '26 21:05

arshajii