我有这个练习和一个算法来实现。我有这个主要的:
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);
}
如果我将“a.contacts()”替换为“a”并使用此类,则代码有效!但是如何使用“a.contacts()”实现 for-each 循环?谢谢
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!!
}