9.14. Looping Through a List

You can use a for-each loop to loop through all of the items in a list, just like you do with an array as shown in the main method below.

Note

The above example isn’t object-oriented since all work was done in the main method. In an object-oriented approach the list would be a field of the current object and you would use an object method rather than a class (static) method to loop through the list.

You can also use a while or for loop to process list elements. Remember that you can use the get(index) to get the value at the index. You can also use remove(index) to remove the value at the index.

Note

Be careful when you remove items from a list as you loop through it. Remember that removing an item from a list will shift the remaining items to the left.

Note

Notice that the method above only increments the current index if an item was not removed from the list. If you increment the index in all cases you will miss checking some of the elements since the rest of the items shift left when you remove one.

Can you change the code above so that it only removes the first name it finds in the list that matches? Can you change it to only remove the last one in the list that matches?

Check your understanding

    8-7-1: Assume that nums has been created as an ArrayList object and it initially contains the following Integer values [0, 0, 4, 2, 5, 0, 3, 0]. What will nums contain as a result of executing numQuest?

    List<Integer> list1 = new ArrayList<Integer>();
    private List<Integer> nums;
    
    // precondition: nums.size() > 0;
    // nums contains Integer objects
    public void numQuest()
    {
       int k = 0;
       Integer zero = new Integer(0);
       while (k < nums.size())
       {
          if (nums.get(k).equals(zero))
             nums.remove(k);
          k++;
       }
    }
    
  • [0, 4, 2, 5, 3]
  • Incrementing the index each time through the loop will miss when there are two zeros in a row.
  • [3, 5, 2, 4, 0, 0, 0, 0]
  • This would be true if the code moved the zeros to the end, but that is not what it does.
  • [0, 0, 0, 0, 4, 2, 5, 3]
  • This would be true if the code moved the zeros to the font, but that is not what it does.
  • [4, 2, 5, 3]
  • This would be correct if k was only incremented when an item was not removed from the list.

You can step through the code above by clicking on the following Example-8-7-1.

    8-7-2: Which of the following is a reason to use a list (assume an object of the class ArrayList) instead of an array?
  • A list will always use less memory than an array.
  • No, an ArrayList grows as needed so it will typically be bigger than the data you put it in. If you try to add more data and the array is full, it usually doubles in size.
  • A list can store objects, but arrays can only store primitive types.
  • No, you can have an array of objects.
  • A list has faster access to the last element than an array.
  • No, an ArrayList is implemented using an array so it has the same access time to any index as an array does.
  • A list resizes itself as necessary as items are added, but an array does not.
  • An ArrayList is really a dynamic array (one that can grow or shrink as needed).

Mixed up programs

        8-7-3: The following has the correct code for the method getScore plus at least one extra unneeded code statement.  This method will calculate and return the score for a word game.  The code should loop through all of the elements in wordList and if the length of the current word is 3 it should add one to the score, if the length of the word is 4 it should add 2 to the score, and if the length is greater than 4 it should add 3 to the score.  The method should return the score.  Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the Check Me button.  You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks.  There is one extra block that is not needed in a correct solution.public static int getScore(List wordList)
{
---
  int score = 0;

  for (String word : wordList)
  {
---
    if (word.length() == 3)
---
    {
      score++;
    }
---
    else if (word.length() == 4)
    {
      score = score + 2;
    }
---
    else
    {
      score = score + 3;
    }
---
  } // end for
---
  return score;

} // end method
---
if (word.length == 3) #distractor
        
        8-7-4: The following has the correct code for a method called insertInOrder plus at least one extra unneeded code statement. This method should add the passed name in alphabetic order to a private list field called nameList.  Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the Check Me button.  You will be told if any of the blocks are in the wrong order or if you need to remove one or more blocks.  There is one extra block that is not needed in a correct solution.public void insertInOrder(String name)
{
---
  int index = 0;
---
  while (index < nameList.size() &&
         nameList.get(index).compareTo(name) < 0)
  {
---
    index++;
---
  } // end while
---
  nameList.add(index,name);
---
} // end method
---
nameList.add(name); #distractor
        
Next Section - 9.15. Comparing Arrays and Lists