简体   繁体   中英

Iterating through a 2D array with the second dimension having different lengths

I have a 2D array in which takes user input to create the first dimension length then loops through and gets the 2nd dimension lengths. Ex: if the user enters 4 for the first dimension it will then loop through 4 times and get the second dimension lengths which could be 2, 3, 2 ,4. I'm not sure how i could effectively loop through this...

You don't actually have to iterate the inner arrays, all you have to do is iterate the outer array and get the length property of each inner array. You could do this with a simple for loop:

int[] arrayLengths = new int[outerArray.length];

for (int i = 0; i < outerArray.length; i++) {
  arrayLengths[i] = outerArray[i].length;
}

Or if you're feeling fancy, using streams :

int[] arrayLengths = Arrays.stream(outerArray)
                         .mapToInt(innerArray -> innerArray.length)
                         .toArray();

Play with this code

import java.util.Arrays;
import java.util.Scanner;

public class MyClass {
    public static void main(String args[]) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Enter number of Arrays that 2D Array( Arrays of Arrays) should contain:");
        int len = sc.nextInt();
        int [][]arr2D = new int[len][];

        for(int i=0; i<len; i++){
            System.out.println("Enter length for Array at index "+i);
            int innerlen = sc.nextInt();
            arr2D[i] = new int[innerlen];
        }

        System.out.println(Arrays.deepToString(arr2D));
    }
}

Output

Enter number of Arrays that 2D Array( Arrays of Arrays) should contain:
5
Enter length for Array at index 0
3
Enter length for Array at index 1
4
Enter length for Array at index 2
5
Enter length for Array at index 3
2
Enter length for Array at index 4
1
[[0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0], [0]]

index 01234
    0|---    <- second dimension length tells how many element array at this index contains
    1|----
    2|-----
    3|--
    4|-

     ^
     | first dimension length tells how many arrays are allowed in array of array

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM