Question

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.

Was it helpful?

Solution

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();
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top