// Tyler Mi // Program showing the limitations and uses of for-each loops and iterators import java.util.*; public class ForEach { public static void main(String[] args) { List list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); // How we would use a for-each loop to print all the elements for (int n : list) { System.out.println(n); // Unfortunatly, we can't add/remove elements from the structure // we are looping over in a for-each loop. This will run into a // ConcurrentModificationException :( list.add(2 * n); } // With lists, we can use a normal for-loop though! int size = list.size(); for (int i = 0; i < size; i++) { list.add(2 * list.get(i)); } System.out.println(list); Set set = new TreeSet<>(); set.addAll(list); System.out.println(set); // Like with Lists, we will also run into a ConcurrentModificationException // if we try to remove the even numbers from the set as we got through it for (int n : set) { if (n % 2 == 0) { set.remove(n); } } // All collections have an .iterator() method that will // give you an Iterator over that data-structure // Iterators will allow you to get all the elements of the structure // like a Scanner, and allow you to remove elements too as you go! Iterator i = set.iterator(); while(i.hasNext()) { int n = i.next(); if (n % 2 == 0) { // Asking the set to remove it won't work, but we can // make the Iterator remove it for us! // set.remove(n); i.remove(); } } System.out.println(set); } }