N
N
Nikita2018-03-17 13:02:19
Java
Nikita, 2018-03-17 13:02:19

Why can foreach take an instance of a class that has an iterator method?

As I understand it, foreach understands the Iterable interface as an array, but why do we need only an instance of the class?

for (String j: new Iterabled()) {
            System.out.println(j);
        }

class Iterabled extends Pets implements Iterable<String>{

    public int size(){
        return names.length;
    }

    @Override
    public Iterator<String> iterator(){
        return new Iterator<String>() {
            private int index = 0;
            @Override
            public boolean hasNext() {
                return index < size();
            }
            @Override
            public String next() {
                index = index + 1;
                return names[index];
            }
        };
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2018-03-17
@NeToster

He understands Iterable not as an array, but as something that can be iterated over. How to enumerate what is inside. For this, an Iterator is returned.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question