In: Computer Science
In Java, you can iterate an ArrayList in different ways. Write the following methods to print Integers in an ArrayList iterating in different ways:
1. // Using basic while / for loop
void printArrayListBasicLoop(ArrayList<Integer> al);
2. // Using enhanced for loop (:)
void printArrayListEnhancedLoop(ArrayList<Integer> al);
3. // Using basic for loop with iterator
void printArrayListForLoopListIterator(ArrayList<Integer>
al);
4. // Using basic while loop with iterator
void printArrayListWhileLoopListIterator(ArrayList<Integer>
al);
import java.util.ArrayList; import java.util.Arrays; import java.util.Iterator; public class LoopArrayLists { // Using basic while / for loop void printArrayListBasicLoop(ArrayList<Integer> al) { for (int i = 0; i < al.size(); i++) { System.out.println(al.get(i)); } } // Using enhanced for loop (:) void printArrayListEnhancedLoop(ArrayList<Integer> al) { for (Integer num : al) { System.out.println(num); } } // Using basic for loop with iterator void printArrayListForLoopListIterator(ArrayList<Integer> al) { for (Iterator<Integer> it = al.iterator(); it.hasNext(); ) { System.out.println(it.next()); } } // Using basic while loop with iterator void printArrayListWhileLoopListIterator(ArrayList<Integer> al) { Iterator<Integer> it = al.iterator(); while (it.hasNext()) { System.out.println(it.next()); } } public static void main(String[] args) { ArrayList<Integer> list = new ArrayList<>(Arrays.asList(3, 8, 1, 9)); new LoopArrayLists().printArrayListBasicLoop(list); System.out.println(); new LoopArrayLists().printArrayListEnhancedLoop(list); System.out.println(); new LoopArrayLists().printArrayListForLoopListIterator(list); System.out.println(); new LoopArrayLists().printArrayListWhileLoopListIterator(list); System.out.println(); } }