对于集合的一个基本的操作利用foreach语句遍历集合以处理集合中的每个元素。看下面的代码:

 

Java代码 Java集合中迭代实现(foreach语句) _中 Java集合中迭代实现(foreach语句) _中_02
  1. // 下面是关于foreach语句的使用,代码非常简洁和紧凑
  2. Stack<String> collection = new Stack<String>();
  3. // ....
  4. for (String s : collection) {
  5. System.out.println(s);
  6. }
  7. // ...
  8.  
  9. // 下面使用while语句来代替上面的foreach语句来实现相同的功能
  10. Stack<String> collection = new Stack<String>();
  11. Iterator<String> iterator = collection.iterator();
  12. while (iterator.hasNext()) {
  13. System.out.println(iterator.next());
  14. }

上面的代码说明为了使用foreach语句我们必须实现可迭代的集合,在Java中就是实现Iterable<T>接口:

 

Java代码 Java集合中迭代实现(foreach语句) _中 Java集合中迭代实现(foreach语句) _中_02
  1. // java.lang.Iterable
  2. public interface Iterable<T> {
  3. Iterator<T> iterator();
  4. }

其实,我们要实现的有两个方面:(1)集合必须实现iterator()方法,并返回一个Iterator(这在Java中也是个接口)对象。(2)Iterator类必须包括两个方法:1.hasNext(),返回一个布尔值。2.next(),返回集合中的一个元素。下面是一个例子:

 

Java代码 Java集合中迭代实现(foreach语句) _中 Java集合中迭代实现(foreach语句) _中_02
  1. import java.util.Iterator;
  2. import java.util.NoSuchElementException;
  3. public class Stack<E> implements Iterable<E>
  4. {
  5. private int size; // size of the stack
  6. private Node first; // top of stack
  7.  
  8. // helper linked list class
  9. private class Node
  10. {
  11. private E element;
  12. private Node next;
  13. }
  14. // create an empty stack
  15. public Stack() {
  16. size = 0;
  17. first = null;
  18. assert check();
  19. }
  20. // Is the stack empty?
  21. public boolean isEmpty() {
  22. return (first == null);
  23. }
  24. // return the number of items in the stack
  25. public int size() {
  26. return size;
  27. }
  28.  
  29. /*
  30. Add the element to the stack.
  31. */
  32. public void push(E element) {
  33. Node oldfirst = first;
  34. first = new Node();
  35. first.element = element;
  36. first.next = oldfirst;
  37. size++;
  38. assert check();
  39. }
  40. /*
  41. Delete and return the item most recently added to the stack.
  42. @throws java.util.NoSuchElementException if the stack is Empty
  43. */
  44.  
  45. public E pop() {
  46. if (isEmpty())
  47. {
  48. throw new NoSuchElementException("Stack underflow");
  49. }
  50. E element = first.element; // save element to return
  51. first = first.next; // delete first node
  52. size--;
  53. assert check();
  54. return element; // return the saved element
  55. }
  56.  
  57. /*
  58. Return the element most recently added to the stack.
  59. @throws java.util.NoSuchElementException if stack is Empty.
  60. */
  61. public E peek() {
  62. if (isEmpty())
  63. {
  64. throw new NoSuchElementException("Stack underflow");
  65. }
  66. return first.element;
  67. }
  68.  
  69. /*
  70. Return string representation.
  71. */
  72.  
  73. public String toString() {
  74. StringBuilder sb = new StringBuilder();
  75. for (E element: this)
  76. {
  77. sb.append(element + "-");
  78. }
  79. return sb.toString();
  80. }
  81.  
  82. /* check internal invariants */
  83. private boolean check() {
  84. if (size == 0)
  85. {
  86. if (first != null)
  87. {
  88. return false;
  89. }
  90. }
  91.  
  92. return true;
  93. }
  94. /* return an iterator to the stack that iterates
  95. through the elemets in LIFO order */
  96. public Iterator<E> iterator() {
  97. return new ListIterator();
  98. }
  99. // an iterator,doesn't implement remove() since it's optional
  100. private class ListIterator implements Iterator<E> {
  101. private Node current = first;
  102. public boolean hasNext() {
  103. return current != null;
  104. }
  105.  
  106. public void remove() {
  107. throw new UnsupportedOperationException();
  108. }
  109.  
  110. public E next() {
  111. if (!hasNext()) {
  112. throw new NoSuchElementException();
  113. }
  114. E element = current.element;
  115. current = current.next;
  116.  
  117. return element;
  118. }
  119. }
  120.  
  121. public static void main(String[] args)
  122. {
  123. Stack<String> s = new Stack<String>();
  124. while (!StdIn.isEmpty())
  125. {
  126. String element = StdIn.readString();
  127. if (!element.equals("-"))
  128. {
  129. s.push(element);
  130. }else if(!s.isEmpty()) {
  131. StdOut.print(s.pop() + " ");
  132. }
  133. }
  134.  
  135. StdOut.println("(" + s.size() + "left on stack)");
  136. }
  137. }