Iterable and Iterator

Solution

Bag<T> must implement Iterable<T>.

Solution
Iterator<String> it = words.iterator();
while (it.hasNext()) {
  String w = it.next();
  System.out.println(w);
}
Solution

A data structure implements Iterable<T> to say it can be iterated over. Its iterator() method returns an Iterator<T>. An Iterator<T> is the object that returns the elements one at a time, through hasNext() and next().

Solution

Each loop calls nums.iterator() and gets its own iterator, with its own position. The inner loop advances only its own iterator, so the outer iterator’s position does not change.