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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With