Question d’entretien chez Google

Create a Java class that receives a collection of collections as parameter and provides basic iterator functions, that is next() and hasNext(). The inner structure (collection of collections) must be hidden by the external interface. The next() method must thus iterate over all the elements of all the collections, starting with the next one if the current ends.

Réponse à la question d'entretien

Utilisateur anonyme

13 févr. 2011

public static class CollectionIterator implements Iterator { private Iterator mMetaIt; private Iterator mCurrentIt; public CollectionIterator(Collection c) { mMetaIt = c.iterator(); } public boolean hasNext() { if (mCurrentIt == null) { if (!mMetaIt.hasNext()) { return false; } mCurrentIt = ((Collection) mMetaIt.next()).iterator(); } while (true) { boolean hasNext = mCurrentIt.hasNext(); if (hasNext) { return true; } if (!mMetaIt.hasNext()) { return false; } mCurrentIt = ((Collection) mMetaIt.next()).iterator(); } } public void remove() { throw new UnsupportedOperationException(); } public Object next() { boolean hasNext = hasNext(); if (!hasNext) { throw new NoSuchElementException(); } return mCurrentIt.next(); } }