4.12 2D Array Traversals

8 阅读2分钟

1. Exam Points

  • Traverse a 2D array using loops (row-major order and column-major order):
    • for loops
    • for-each loops (enhanced for loops)
  • Traverse 2D arrays and ArrayLists.
  • Index out of range: ArrayIndexOutOfBoundsException.
  • Analyze how many times a statement is executed.
  • Note: how row indexes or column indexes change: ++, +=2, --

2. Knowledge Points

(1) Traverse 2D arrays : for Loops

  • Nested iteration/loop statements are used to traverse and access elements in a 2D array.
  • Since a 2D array is stored as an array of arrays, the way 2D arrays are traversed using for loops and for-each loops(enhanced for loops) is similar to 1D arrays.
  • You can traverse a 2D array in:
    • row-major order: across each row, such as 1st row, then 2nd row, ...
      • Example:
      
      // outer loop for accessing each row
      // i represents the index of each row
      for (int i = 0; i < nums.length; i++) { 
      
          // inner loop for accessing all the columns in one row
          // j is the column index
          for (int j = 0; j < nums[0].length; j++) { 
              System.out.print(nums[i][j] + " ");
          }
      	
          // start a new line after printing all the elements in one row
          System.out.println();
      }	
      
    • column-major order: across each column, such as 1st column, then 2nd column, ...
      • Example:
      
      // in this example, i is the column index, j is the row index
      
      // is is the column index
      for(int i=0; i < nums[0].length; i++) {
      	
          for(int j=0; j < nums.length; j++) { // j is the row index
              System.out.print(nums[j][i] + " ");
          }
      	
          System.out.println();
      }
      
    • uniquely defined order

(2) Traverse 2D arrays : for-each Loops

  • Remember: A 2D array is an array of arrays.

  • Example 1: traverse an int array

    int[][] nums = { 
            { 1, 2, 3, 4 }, 
            { 5, 6, 7, 8 }, 
            { 9, 10, 11, 12 } 
    };
    
    // arr represents each row, each row is an 1D array 
    for (int[] arr : nums) {
    
        for (int x : arr) { // x means the current element
            System.out.print(x + " ");
        }
    
        // start a new line after printing all the elements of a row
        System.out.println();
    }
    
  • Example 2: traverse a String array

    String[][] words = { 
            { "dog", "pig", "cat", "snake" }, 
            { "apple", "orange", "pear", "banana" },
            { "black", "white", "pink", "red" } 
    };
    
    // arr represents each row, each row is an 1D array 	
    for (String[] arr : words) {
    
        for (String x : arr) { // x means the current element
            System.out.print(x + " ");
        }
    
        System.out.println();
    }
    
  • Example 3: traverse a Dog array

    class Dog {
    
        private String name;
        private int age;
    
        public Dog(String n, int a) {
            name = n;
            age = a;
        }
    
        public String getName() {
            return name;
        }
    
        public int getAge() {
            return age;
        }
    }
    
    public class MainClass {
    
        public static void main(String[] args) {
    
            Dog[][] dogs = new Dog[2][3];
    	
            // for an array of object references, you need to instantiate each element
            
            // create Dog objects of the first row
            dogs[0][0] = new Dog("lele",3);
            dogs[0][1] = new Dog("haha",1);
            dogs[0][2] = new Dog("hehe",4);
                
            // create Dog objects of the second row
            dogs[1][0] = new Dog("doudou",5);
            dogs[1][1] = new Dog("keke",6);
            dogs[1][2] = new Dog("koko",8);
    	
            // lele     haha   hehe
            // doudou   keke   koko
    	
            // 1. using for loops
            for(int i=0; i < dogs.length; i++) { // i: row index
    		
                for(int j=0; j < dogs[0].length; j++) { // j: column index
                    Dog d=dogs[i][j];
                    System.out.print(d.getName() + "-" + d.getAge() + "     ");
                }
    		
                System.out.println();
            }
    	
            System.out.println("----------------------------------");
    	
            // 2. using for-each loops
    	
            for(Dog[] arr : dogs) {
    		
                for(Dog d : arr) {
                    System.out.print(d.getName() + "-" + d.getAge() + "     ");
                }
    		
                System.out.println();
    	}
    }
    

(3) Traverse 2D arrays : for-each + for Loops

  • You may combine a for loop and a for-each loop while traversing a 2D array.
  • Example:
    int[][] nums = { 
        { 1, 2, 3, 4 }, 
        { 5, 6, 7, 8 }, 
        { 9, 10, 11, 12 } 
    };
    	
    // using for-each loop(outer) + for loop(inner)
    for(int[] row:nums) {
    		
        for(int j=0;j < row.length;j++) {
            System.out.print(row[j] + " ");
        }
    		
        System.out.println();
    }
    

3. Exercises