When making my collection class Iterable (implementing Iterable) what do I have in the iterator() method?

StackOverflow https://stackoverflow.com/questions/19084817

문제

I've read so many tutorials, but they all seem to have so many differing contents for the inside of the iterator() method. I have a class that holds many Animals, so I have it implements Iterable<Animal> as they're Animal objects, but what do I return in public Iterator<Animal> iterator() { ... }? I want to be able to use it in a for-each loop.

도움이 되었습니까?

해결책

Well, if it has many Animals, you will want to return an Iterator<Animal>. Try this code, for starters:

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
        }
    }
}

If you already store the Animals in an array, you can use just one line of code:

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

And if you store it in any type of Collection<Animal> (such as an ArrayList):

public Iterator<Animal> iterator() {
    return yourAnimalCollection.iterator();
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top