java迭代器是什么意思,返回迭代器是什么意思? Java的

I have to write a class that implements the Iterable interface. I'm confused about what it means to return an iterator object. An iterator just goes through the elements of a list, so how would I return this as an object? Would I return a list that was able to be iterated through or what? How can an iterator be an object when all it does is go through or change data in other objects?

解决方案

Here is an example of a very simplistic list. It represents the list as linked elements.

The iterator object is created as an anonymous inner class holding the current element as the state. Each call of iterator() creates a new iterator object.

import java.util.Iterator;

public class SimplisticList implements Iterable {

/*

* A list element encapsulates a data value and a reference to the next

* element.

*/

private static class Element {

private T data;

private Element next;

Element(T data) {

this.data = data;

next = null;

}

public T getData() {

return data;

}

public Element getNext() {

return next;

}

public void setNext(Element next) {

this.next = next;

}

}

// We only need a reference to the head of the list.

private Element first = null;

// The list is empty if there is no first element.

public boolean isEmpty() {

return first == null;

}

// Adding a new list element.

// For an empty list we only have to set the head.

// Otherwise we have to find the last element to add the new element.

public void add(T data) {

if(isEmpty()) {

first = new Element(data);

} else {

Element current = first;

while(current.getNext() != null) {

current = current.getNext();

}

current.setNext(new Element(data));

}

}

@Override

public Iterator iterator() {

// Create an anonymous implementation of Iterator.

// We need to store the current list element and initialize it with the

// head of the list.

// We don't implement the remove() method here.

return new Iterator() {

private Element current = first;

@Override

public boolean hasNext() {

return current != null;

}

@Override

public T next() {

T result = null;

if(current != null) {

result = current.getData();

current = current.getNext();

}

return result;

}

@Override

public void remove() {

// To be done ...

throw new UnsupportedOperationException();

}

};

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值