Arrays are a fundamental data structure in programming that allow you to store and manipulate large sets of data. A deep array is an array that contains other arrays as elements called also  multidimensional array. This can be a powerful tool for organizing and structuring your data, but it can also make outputting the contents of the array more complex. In this article, we will discuss how to use deep array output in Java.

  1. Using a nested for loop

One of the simplest ways to output the contents of a deep array is to use a nested for loop. Here’s an example:

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

for (int i = 0; i < deepArray.length; i++) {
    for (int j = 0; j < deepArray[i].length; j++) {
        System.out.print(deepArray[i][j] + " ");
    }
    System.out.println();
}

Output:

1 2 3 
4 5 6 
7 8 9 

In this example, we have a deep array called deepArray that contains three sub-arrays, each with three integers. We use a nested for loop to iterate over the array, printing out each element using the System.out.print() method. We also use System.out.println() to print a newline after each row.

  1. Using the Arrays.deepToString() method

Java provides a utility method called deepToString() in the Arrays class that can be used to convert a deep array into a string representation. Here’s an example:

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

String output = Arrays.deepToString(deepArray);
System.out.println(output);

Output:

[[1, 2, 3], [4, 5, 6], [7, 8, 9]]

In this example, we use the Arrays.deepToString() method to convert the deepArray into a string, which we then print to the console using System.out.println().

  1. Using recursion

Another approach to outputting the contents of a deep array is to use recursion. Here’s an example:

public static void printDeepArray(int[][] deepArray) {
    for (int i = 0; i < deepArray.length; i++) {
        if (deepArray[i].length == 0) {
            System.out.println("[]");
        } else if (deepArray[i].length == 1) {
            System.out.print(deepArray[i][0] + " ");
        } else {
            int[][] newArray = new int[deepArray.length - 1][];
            for (int j = 0; j < newArray.length; j++) {
                newArray[j] = deepArray[j + 1];
            }
            printDeepArray(newArray);
        }
    }
}

Output:

1 2 3 4 5 6 7 8 9 

In this example, we define a recursive method called printDeepArray() that takes a deep array as input. The method checks if each sub-array has length 0 or 1. If so, it prints out the appropriate value using System.out.println() or System.out.print(). If the sub-array has length greater than 1, the method creates a new deep array without the first element and calls itself

Aller au contenu principal