This book is now obsolete Please use CSAwesome instead.

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

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

Mixed up programs

The following has the correct code for the method <code>getScore</code> 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 <code>wordList</code> and if the length of the current word is 3 it should add one to the <code>score</code>, if the length of the word is 4 it should add 2 to the <code>score</code>, and if the length is greater than 4 it should add 3 to the <code>score</code>. The method should return the <code>score</code>. Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the <i>Check Me</i> 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.

The following has the correct code for a method called <code>insertInOrder</code> plus at least one extra unneeded code statement. This method should add the passed <code>name</code> in alphabetic order to a private list field called <code>nameList</code>. Drag the needed blocks from the left into the correct order on the right. Check your solution by clicking on the <i>Check Me</i> 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.

You have attempted of activities on this page