What happens if the following code is executed?

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

public class Test<T> implements Iterable<T>{   // 1

    private List<T> list = new ArrayList<T>();

    public void addList(T... ts) {
        Collections.addAll(list, ts); 
    }

    public static void main(String... args) {
        Test<String> t  = new Test<String>();  
        t.addList("Hello", "world", "!");      
        for (String str : t) {                 // 2
            System.out.print(str + " ");
        }
    }

    public Iterator<T> iterator() {
        return new Iterator() {                // 3               

            private int index = 0;

            public boolean hasNext() {
                return index < list.size();
            }

            public Object next() {
                return list.get(index++);
            }

            public void remove() {
                throw new UnsupportedOperationException("unsupported operation");
            }
        };
    }
}
Explanation
The Iterable and Iterator interfaces are correctly implemented, hence lines 1 and 3 do not contain errors.
The Java for-each loop works with two types of objects: arrays of any type, and classes that implement the Iterable interface, which is our case, hence line 2 will not cause any errors.

Follow CodeGalaxy

Mobile Beta

Get it on Google Play
Send Feedback
Keep exploring
Java quizzes
Cosmo
Sign Up Now
or Subscribe for future quizzes