4.4 Array Traversals

10 阅读1分钟

1. Exam Points

  • Traverse an array using for loops (use indexes).
  • Traverse an array using while loops (use indexes).
  • Traverse an array using for-each loops (not use indexes).
  • Assigning a new value to the enhanced for loop variable does not change the value stored in the array (applys to arrays storing primitive values).
  • Traverse part of the elements of an array. (index += 2, etc.)

2. Knowledge Points

(1) Traverse Arrays

  • Traversing an array is when repetition statements (loop) are used to access all or some of the elements in an array.
  • Loops commonly used for array traversals.
    • for loops (use indexes)
    • while loops (use indexes)
    • for-each loops, i.e, enhanced for loops (no use of indexes)
  • Traverse an 1D array of primitive values.
    • Example:
      int[] nums = { 1, 2, 3, 4 };
      // 1. for loop (use indexes)
      for (int i = 0; i < nums.length; i++) { 
          // i is an index, nums[i] is an element
          System.out.print(nums[i] + " ");
      }
      
      System.out.println();
      
      // 2. while loop (use indexes)
      int j = 0;
      while(j < nums.length ){
          // j is an index, nums[j] is an element
          System.out.print(nums[j] + " ");
          j++;
      }
      
      System.out.println();
      
      System.out.println();
      // 3. for-each loop (no use of indexes)
      for (int x : nums) { // here type 'int' follows the type of the array
          // here x is the current element
          System.out.print(x + " ");
      }
      
  • Traverse an 1D array of object references.
    • Example:
      class Pig {
          
          private String name;
          private boolean vaccinated;
          
          public Pig(String n, boolean v) {
              name = n;
              vaccinated = v;
          }
          
          public String getName() {
              return name;
          }
          
          public boolean isVaccinated() {
              return vaccinated;
          }
      }
      
      // 1. use for loops
      for (int i = 0; i < pigs.length; i++) {
          System.out.println(pigs[i].getName() + "-" + pigs[i].isVaccinated());
      }
      
      // 2. use for-each loops
      for (Pig p : pigs) {
          System.out.println(p.getName() + "-" + p.isVaccinated());
      }
      

3. Exercises