ArrayIterator.java 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /**
  2. * ArrayIterator represents an iterator over the elements of an array.
  3. *
  4. * @author Dr. Lewis
  5. * @author Dr. Chase
  6. * @version 1.0, 8/19/08
  7. */
  8. import java.util.*;
  9. public class ArrayIterator<T> implements Iterator
  10. {
  11. private int count; // the number of elements in the collection
  12. private int current; // the current position in the iteration
  13. private T[] items;
  14. /**
  15. * Sets up this iterator using the specified items.
  16. *
  17. * @param collection the collection for which the iterator will be created
  18. * @param size the size of the collection
  19. */
  20. public ArrayIterator (T[] collection, int size)
  21. {
  22. items = collection;
  23. count = size;
  24. current = 0;
  25. }
  26. /**
  27. * Returns true if this iterator has at least one more element
  28. * to deliver in the iteraion.
  29. *
  30. * @return true if this iterator has at least one more element to deliver
  31. */
  32. public boolean hasNext()
  33. {
  34. return (current < count);
  35. }
  36. /**
  37. * Returns the next element in the iteration. If there are no
  38. * more elements in this itertion, a NoSuchElementException is
  39. * thrown.
  40. *
  41. * @return the next element in the iteration
  42. * @throws NoSuchElementException if a no such element exception occurs
  43. */
  44. public T next()
  45. {
  46. if (! hasNext())
  47. throw new NoSuchElementException();
  48. current++;
  49. return items[current - 1];
  50. }
  51. /**
  52. * The remove operation is not supported in this collection.
  53. *
  54. * @throws UnsupportedOperationException if an unsupported operation
  55. * exception occurs
  56. */
  57. public void remove() throws UnsupportedOperationException
  58. {
  59. throw new UnsupportedOperationException();
  60. }
  61. }