import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class IteratorExample { public static void main(String[] args) { // Create an ArrayList and add some elements List<String> arrayList = new ArrayList<>(); arrayList.add("Apple"); arrayList.add("Banana"); arrayList.add("Cherry"); // Create a LinkedList and add some elements List<String> linkedList = new LinkedList<>(); linkedList.add("Dog"); linkedList.add("Elephant"); linkedList.add("Frog"); // Iterate over the ArrayList System.out.println("ArrayList elements:"); Iterator<String> arrayListIterator = arrayList.iterator(); while (arrayListIterator.hasNext()) { String element = arrayListIterator.next(); System.out.println(element); } // Iterate over the LinkedList System.out.println("\nLinkedList elements:"); Iterator<String> linkedListIterator = linkedList.iterator(); while (linkedListIterator.hasNext()) { String element = linkedListIterator.next(); System.out.println(element); } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter