对于集合的一个基本的操作利用foreach语句遍历集合以处理集合中的每个元素。看下面的代码:
// 下面是关于foreach语句的使用,代码非常简洁和紧凑
Stack<String> collection = new Stack<String>();
// ....
for (String s : collection) {
System.out.println(s);
}
// ...
// 下面使用while语句来代替上面的foreach语句来实现相同的功能
Stack<String> collection = new Stack<String>();
Iterator<String> iterator = collection.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
上面的代码说明为了使用foreach语句我们必须实现可迭代的集合,在Java中就是实现Iterable<T>接口:
// java.lang.Iterable
public interface Iterable<T> {
Iterator<T> iterator();
}
其实,我们要实现的有两个方面:(1)集合必须实现iterator()方法,并返回一个Iterator(这在Java中也是个接口)对象。(2)Iterator类必须包括两个方法:1.hasNext(),返回一个布尔值。2.next(),返回集合中的一个元素。下面是一个例子:
import java.util.Iterator;
import java.util.NoSuchElementException;
public class Stack<E> implements Iterable<E>
{
private int size; // size of the stack
private Node first; // top of stack
// helper linked list class
private class Node
{
private E element;
private Node next;
}
// create an empty stack
public Stack() {
size = 0;
first = null;
assert check();
}
// Is the stack empty?
public boolean isEmpty() {
return (first == null);
}
// return the number of items in the stack
public int size() {
return size;
}
/*
Add the element to the stack.
*/
public void push(E element) {
Node oldfirst = first;
first = new Node();
first.element = element;
first.next = oldfirst;
size++;
assert check();
}
/*
Delete and return the item most recently added to the stack.
@throws java.util.NoSuchElementException if the stack is Empty
*/
public E pop() {
if (isEmpty())
{
throw new NoSuchElementException("Stack underflow");
}
E element = first.element; // save element to return
first = first.next; // delete first node
size--;
assert check();
return element; // return the saved element
}
/*
Return the element most recently added to the stack.
@throws java.util.NoSuchElementException if stack is Empty.
*/
public E peek() {
if (isEmpty())
{
throw new NoSuchElementException("Stack underflow");
}
return first.element;
}
/*
Return string representation.
*/
public String toString() {
StringBuilder sb = new StringBuilder();
for (E element: this)
{
sb.append(element + "-");
}
return sb.toString();
}
/* check internal invariants */
private boolean check() {
if (size == 0)
{
if (first != null)
{
return false;
}
}
return true;
}
/* return an iterator to the stack that iterates
through the elemets in LIFO order */
public Iterator<E> iterator() {
return new ListIterator();
}
// an iterator,doesn't implement remove() since it's optional
private class ListIterator implements Iterator<E> {
private Node current = first;
public boolean hasNext() {
return current != null;
}
public void remove() {
throw new UnsupportedOperationException();
}
public E next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
E element = current.element;
current = current.next;
return element;
}
}
public static void main(String[] args)
{
Stack<String> s = new Stack<String>();
while (!StdIn.isEmpty())
{
String element = StdIn.readString();
if (!element.equals("-"))
{
s.push(element);
}else if(!s.isEmpty()) {
StdOut.print(s.pop() + " ");
}
}
StdOut.println("(" + s.size() + "left on stack)");
}
}