Reputation: 1512
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.
Upvotes: 3
Views: 124
Reputation: 3078
You can do it with simple instanceof
, for example:
if (obj instanceof Integer[][])
System.out.println("2d");
if (obj instanceof Integer[])
System.out.println("1d");
if (obj instanceof Integer)
System.out.println("0d");
Upvotes: 0
Reputation: 129497
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
Upvotes: 7