title: Java implement Iterable, for each and method
body: <p>I've this exercise with an algorithm to implement. I have this main:</p>
  
  <pre><code>    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);
  }
  </code></pre>
  
  <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</p>
  
  <pre><code>class Person implements Iterable&lt;Person&gt; {
  
      private Set&lt;Person&gt; friends = new HashSet&lt;Person&gt;();   
      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&lt;Person&gt; iterator() {
          Iterator&lt;Person&gt; i = friends.iterator();
          return i;
      }
  
      //Here the contacts method to implement!!
  
  }
  </code></pre>