java集合迭代_Java集合中迭代实现(foreach语句)

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

Java代码 icon_copy.gificon_star.png

spinner.gif

// 下面是关于foreach语句的使用,代码非常简洁和紧凑

Stack collection = new Stack();

// ....

for (String s : collection) {

System.out.println(s);

}

// ...

// 下面使用while语句来代替上面的foreach语句来实现相同的功能

Stack collection = new Stack();

Iterator iterator = collection.iterator();

while (iterator.hasNext()) {

System.out.println(iterator.next());

}

// 下面是关于foreach语句的使用,代码非常简洁和紧凑

Stack collection = new Stack();

// ....

for (String s : collection) {

System.out.println(s);

}

// ...

// 下面使用while语句来代替上面的foreach语句来实现相同的功能

Stack collection = new Stack();

Iterator iterator = collection.iterator();

while (iterator.hasNext()) {

System.out.println(iterator.next());

}

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

Java代码 icon_copy.gificon_star.png

spinner.gif

// java.lang.Iterable

public interface Iterable {

Iterator iterator();

}

// java.lang.Iterable

public interface Iterable {

Iterator iterator();

}

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

Java代码 icon_copy.gificon_star.png

spinner.gif

import java.util.Iterator;

import java.util.NoSuchElementException;

public class Stack implements Iterable

{

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 iterator() {

return new ListIterator();

}

// an iterator,doesn't implement remove() since it's optional

private class ListIterator implements Iterator {

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 s = new Stack();

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)");

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值