vendredi 21 décembre 2018

Why do I get a foreach compiler error even though Iterable is implemented?

I'm trying to learn different design patterns in OOP and the current one I'm learning is iterator pattern. Therefore I have made two own interfaces (Iterable and Iterator).

I'm trying to iterate over List<Person> friends. But the row: for (Person p : p1) gives the following compiler error:

foreach not applicable to type 'com.company.Person'

Which to me makes no sense since I've implemented Iterable and overrided the iterator() method as far as I can see.

Can someone tell me what I'm missing?

Here is my code:

Main class:

Person p1 = new Person("Erik");
    p1.addFriend("Lars");
    p1.addFriend("Jenny");
    p1.addFriend("Janne");


    for (Person p : p1) {
        System.out.println(p.name);
    }

Iterator:

public interface Iterator<T> {

    boolean hasNext();

    T next();

    void remove();
}

Iterable:

public interface Iterable<T> {
    Iterator<T> iterator();
}

Person:

public class Person implements Iterable<Person>{
    private List<Person> friends = new ArrayList<>();
    String name;
    int index = 0;
    public Person(String name){
        this.name = name;
    }

    public void addFriend(String name){
        friends.add(new Person(name));
    }

    @Override
    public Iterator<Person> iterator(){
        return new Iterator<Person>() {
            //int index = 0;
            @Override
            public boolean hasNext() {
                System.out.println(index);
                return index < friends.size();

            }    

            @Override
            public Person next() {
                if(hasNext()){
                    return friends.get(index++);
                }
                else{
                    return null;
                }
            }
            @Override
            public void remove() {
                if(index<=0) {
                    friends.remove(index--);
                }
            }
        };
    }
}

Aucun commentaire:

Enregistrer un commentaire