异想维度 java,在抽象Java数组的维度

In Java, arrays of different dimensionalities have different types. So a method that takes int[] as a parameter cannot take int[][] or int[][][]. I have a lot of code where I create methods that are quite similar but for the dimensionality of the array. Is there a way to handle arrays of arbitrary dimensionality, and thus abstract out this common functionality?

解决方案

If you are willing to forego type safety, you can do it with a little recursion (no surprise here, right?) and reflection.

The idea is to write your method in a way that it recurses down until the array has only one dimension. Once you're at the single-dimension level, do the work; otherwise, call yourself recursively, and aggregate your findings from the prior levels if necessary.

Here is a quick demo:

import java.util.*;

import java.lang.*;

import java.lang.reflect.Array;

class Main {

public static int sumArray(Object array) {

Class type = array.getClass();

if (!type.isArray()) {

throw new IllegalArgumentException("array");

}

Class ct = type.getComponentType();

int res = 0;

int len = Array.getLength(array);

if (ct.isArray()) {

for (int i = 0 ; i != len ; i++) {

res += sumArray(Array.get(array, i));

}

} else {

for (int i = 0 ; i != len ; i++) {

res += Array.getInt(array, i);

}

}

return res;

}

public static void main (String[] args) throws java.lang.Exception

{

int[] a = new int[] {1,2,3,4,5,6,7,8,9,10};

int aa[][] = new int[][] {{1,2},{3,4},{5,6}};

int aaa[][][] = new int[][][]{{{1,2},{3,4},{5,6}},{{7,8},{9,10},{11,12}}};

System.out.println(sumArray(a));

System.out.println(sumArray(aa));

System.out.println(sumArray(aaa));

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值