java - What is the argument's type for a method that takes indefinite nested arrays?
问题描述
I am trying to build a static method that traverses a nested array of arrays. I would like to set this method argument to accept any number of nested arrays. In other words, this function should be able to operate an array of arrays or an array of array of arrays (for example).
I illustrate here with an example:
private static void doStuffWithArrays(someType arrays){
//Do some stuff
}
What is the right data type to be in place of someType
?
解决方案
You should use Object[]
.
Methods in the JDK that takes an arbitrarily nested array, like deepToString
, do this too.
Since you don't know whether an object in that outermost array is an inner array, you would have to check getClass().isArray()
:
private static void doStuffWithArrays(Object[] outermostArray){
for (int i = 0 ; i < outermostArray.length ; i++) {
Object outerElement = outermostArray[i];
if (outerElement.getClass().isArray()) {
Object[] innerArray = (Object[])outermostArray[i];
// ... do things with innerArray
} else {
// we reached the innermost level, there are no inner arrays
}
}
}
If you are dealing with arrays of primitives, however, you would need to check each of the primitive array classes separately, then cast to the correct one.
if (outerElement.getClass() == int[].class) {
int[] innerArray = (int[])outermostArray[i];
// ... do things with innerArray
} else if (outerElement.getClass() == short[].class) {
short[] innerArray = (short[])outermostArray[i];
// ... do things with innerArray
} else if (outerElement.getClass() == long[].class) {
long[] innerArray = (long[])outermostArray[i];
// ... do things with innerArray
} else if ... // do this for all the other primitive array types
} else if (outerElement.getClass().isArray()) {
Object[] innerArray = (Object[])outermostArray[i];
// ... do things with innerArray
} else {
// we reached the innermost level, there are no inner arrays
}
deepToString
does this too.
推荐阅读
- php - 抽象方法没有被嘲笑
- c++ - 模板代码的 Intellisense 弹出窗口 (Visual Studio 2019)
- r - 有没有办法将处理过的表格保存回原始 Excel 文件,以便它可以有两张纸?1. 原创 2. 编辑
- laravel - 将我的网络摄像头的 Blob 原始数据从 Vue-axios 发送到 Laravel 后端
- arduino - 如何从未定义数量的按钮控制器中获取输入
- python - 如何转换和求和持续时间?
- assembly - 用于在 MessageBox 中输出单独行的 MASM 宏
- python - 转换长数据帧并提取字符串
- python - 有条件地添加日期
- angular - 是否有必要在后端服务中取消订阅/完成以防止副作用?