3

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.

6
  • Is there a specific reason why you're not just using 2 overloads? Commented Oct 19, 2013 at 21:14
  • if(myarray[I] instanceof type) ....; think this is what you want? Commented Oct 19, 2013 at 21:15
  • @JeroenVannevel Not sure what an overload is :P Commented Oct 19, 2013 at 21:17
  • @pedromss obj could have any number of dimensions, meaning lots and lots of if statements Commented Oct 19, 2013 at 21:18
  • Related to stackoverflow.com/questions/5670972/…. You should have a good reason of wanting to do this. It sounds like a XY problem to me. Maybe you should give us more context on why you want to do this. Commented Oct 19, 2013 at 21:19

2 Answers 2

7

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
Sign up to request clarification or add additional context in comments.

3 Comments

This will cause a ClassCastException if you call it like this arraySum(new Object()). There should be an additional check for an array type obj.getClass().isArray() before the cast in the for loop and of course a null check.
@A4L "a precondition for this method is that obj be an Integer array of any dimension" Although the OP can add those checks if he really needs them. It's a trivial addition, and the core of the method will remain the same.
OP must then make sure to pass only arrays to it. +1 still an elegant solution!
0

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");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.