3

我有以下方法:

public static int arraySum(Object obj) {
}

该方法应返回 obj 中所有元素的总和;该方法的一个前提是它obj是一个任意维度的整数数组,即Integer, Integer[], Integer[][], 等等。

为了编写方法的主体arraySum(),我使用了 foreach 循环和递归;但是,对于 foreach 循环,我需要知道 obj 的元素是哪种类型。有没有办法找出 的类型(即Integer,Integer[]等)obj

编辑:这是我的 CS 课程的作业。我不想简单地问如何编写方法,这就是我问这样一个具体问题的原因。

4

2 回答 2

7

我相信它比你想象的要简单:

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;
}

基本上,我们利用了Integer任意维度的数组仍然是Object[].


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

System.out.println(arraySum(obj));
55
于 2013-10-19T21:22:10.407 回答
0

你可以用 simple 来做到这一点instanceof,例如:

if (obj instanceof Integer[][]) 
    System.out.println("2d");
if (obj instanceof Integer[]) 
    System.out.println("1d");
if (obj instanceof Integer) 
    System.out.println("0d");
于 2013-10-19T21:23:16.730 回答