I’ve this exercise with an algorithm to implement. I have this main:
public static void main(String[] args) {
Person a = new Person("Tony");
Person c = new Person("Luke");
Person o = new Person("Ann");
a.addFriends(c);
a.addFriends(o);
for(Person p: a.contacts())
System.out.println(p);
}
If I replace “a.contacts()” with “a” and use this class, the code works! But How can I implement the for-each loop with “a.contacts()”?? Thanks
class Person implements Iterable<Person> {
private Set<Person> friends = new HashSet<Person>();
private String name;
public Person(String name){
this.name = name;
}
public void addFriends(Person o){
friends.add(o);
}
public String toString(){
return this.name;
}
@Override
public Iterator<Person> iterator() {
Iterator<Person> i = friends.iterator();
return i;
}
//Here the contacts method to implement!!
}
Since you want to run a loop for
Personso the place next to:should be a collection of typePerson.You could either choose a
ListorSetfor this and return the collection fromcontacts()method of classPerson.In this case since you’ve have
Setso return it.