Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Rewrite the following code which iterates through every element of a LinkedList

ID: 3891270 • Letter: R

Question

Rewrite the following code which iterates through every element of a LinkedList and outputs it, replacing the counting for-loop with each of the following:

a. an iterator for-loop

b. a while loop using hasNext on an Iterator created from the LinkedList.

c. a forEach method call

Each part is worth 4 points. Only replace the loop itself, do not bother rewriting the first two lines of code below.

LinkedList<String> list = new LinkedList<>();

list.add(...); list.add(...); ...; list.add(...);

for(int i=0;i<list.size();i++) System.out.println(list.get(i));

Explanation / Answer

import java.util.*;

import java.util.Iterator;

public class LinkedList{

   public static void main(String args[]) {

     

      /*LinkedList declaration*/

     

      LinkedList<String> list = new LinkedList<String>();

     

      list.add("Red");

     

      list.add("Blue");

     

      list.add("Green");

      /*Iterator for loop*/

      for(String s : list)

      {

         System.out.println(s);

    }

      /*while loop using hasNext()*/

      Iterator i = list.iterator();

      while(i.hasNext())

      {

                     System.out.println(i.next());

      }

   }

}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote