2013-09-30 6 views
-1

많은 튜토리얼을 읽었지만 모두 iterator() 메소드 내부에 많은 다른 내용이있는 것 같습니다. 동물을 많이 보유하고있는 클래스가 있으므로 implements Iterable<Animal> 오브젝트가 Animal 오브젝트인데 무엇을 반환합니까? public Iterator<Animal> iterator() { ... }은 무엇입니까? for-each 루프에서 사용할 수 있기를 원합니다.Iterable (Iterable 구현) 컬렉션 클래스를 만들 때 iterator() 메서드에 무엇이 있습니까?

+0

당신은'Iterator' 구현을 반환해야합니다. –

답변

4

글쎄, 많은 경우 Animals이있는 경우 Iterator<Animal>을 반환 할 수 있습니다. 이미 배열의 Animal의를 저장하는 경우, 당신은 한 줄의 코드를 사용할 수 있습니다

public Iterator<Animal> iterator() { 
    return new Iterator<Animal>() { 
     public boolean hasNext() { 
      // your code here 
     } 
     public Animal next() { 
      // your code here 
     } 
     public void remove() { 
      // you really don't need to do anything here unless you want to 
     } 
    } 
} 

: 우선,이 코드를 시도

public Iterator<Animal> iterator() { 
    return Arrays.asList(yourAnimalArray).iterator(); 
} 

을 그리고 당신은 모든 종류의에 저장하는 경우 Collection<Animal> (예 : ArrayList int로서) :

public Iterator<Animal> iterator() { 
    return yourAnimalCollection.iterator(); 
} 
+0

멋지게 완료되었습니다. 1+ –