Estoy tratando de construir un método estático que atraviese una matriz anidada de matrices. Me gustaría establecer este argumento de método para aceptar cualquier número de matrices anidadas. En otras palabras, esta función debería poder operar una matriz de matrices o una matriz de matrices de matrices (por ejemplo).
Ilustro aquí con un ejemplo:
private static void doStuffWithArrays(someType arrays){ //Do some stuff } ¿Cuál es el tipo de datos correcto para estar en lugar de someType ?
Deberías usar Object[] .
Los métodos en el JDK que toman una matriz anidada arbitrariamente, como deepToString , también hacen esto.
Dado que no sabe si un objeto en esa matriz más externa es una matriz interna, debe verificar 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 } } }Sin embargo, si está tratando con matrices de primitivas, deberá verificar cada una de las clases de matrices primitivas por separado y luego convertirlas en la correcta.
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 también hace esto.