What happens when you run the following code?

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

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

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

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

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

    public Iterator<T> iterator() {
        return list.iterator();
    }

}
Explanation
For successful implementation of the Iterator class you need to implement these methods: hasNext(), next(), remove(). So, there's compilation error in line 1. In for-each loop you can use arrays, collections and classes, which implement Iterable interface, so - compilation error will occur in line 4.
For successful execution you need to change Iterator interface to Iterable

Следи за CodeGalaxy

Мобильное приложение Beta

Get it on Google Play
Обратная Связь
Продолжайте изучать
тесты по Java
Cosmo
Зарегистрируйся сейчас
или Подпишись на будущие тесты