Fhernd

AirForceIterator.java

Feb 27th, 2026
16,741
0
Never
2
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.51 KB | Source Code | 0 0
  1. public class AirForceIterator implements Iterator {
  2.  
  3.     List<IAircraft> jets;
  4.     IAircraft[] helis;
  5.     LinkedList<Boeing747> cargo;
  6.     int jetsPosition = 0;
  7.     int helisPosition = 0;
  8.     int cargoPosition = 0;
  9.  
  10.     /**
  11.      * The iterator is composed with the object it'll be iterating over
  12.      */
  13.     public AirForceIterator(AirForce airForce) {
  14.         jets = airForce.getJets();
  15.         helis = airForce.getHelis();
  16.         cargo = airForce.getCargo();
  17.  
  18.     }
  19.  
  20.     @Override
  21.     /**
  22.      * We provide our own custom logic of returning aircraft in a
  23.      * sequence. Note we are returning IAircraft interface object which
  24.      * every plane in our airforce implements. We also design the function
  25.      * to throw a runtime exception if next is invoked when no more elements
  26.      * are left to iterate over
  27.      */
  28.     public IAircraft next() {
  29.  
  30.         // return helis first
  31.         if (helisPosition < helis.length) {
  32.             return helis[helisPosition++];
  33.         }
  34.  
  35.         // return jets second
  36.         if (jetsPosition < jets.size()) {
  37.             return jets.get(jetsPosition++);
  38.         }
  39.  
  40.         // return cargos last
  41.         if (cargoPosition < cargo.size()) {
  42.             return cargo.get(cargoPosition++);
  43.         }
  44.  
  45.         throw new RuntimeException("No more elements");
  46.  
  47.     }
  48.  
  49.     @Override
  50.     public boolean hasNext() {
  51.  
  52.         return helis.length > helisPosition ||
  53.                jets.size() > jetsPosition ||
  54.                cargo.size() > cargoPosition;
  55.     }
  56. }
Advertisement