問題描述
我正在嘗試理解 Java Iterator
和 Iterable
接口
I am trying to understand Java Iterator
and Iterable
interfaces
我正在寫這門課
class MyClass implements Iterable<String> {
public String[] a = null;
public MyClass(String[] arr) {
a = arr;
}
public MyClassIterator iterator() {
return new MyClassIterator(this);
}
public class MyClassIterator implements Iterator<String> {
private MyClass myclass = null;
private int count = 0;
public MyClassIterator(MyClass m) {
myclass = m;
}
public boolean hasNext() {
return count < myclass.a.length;
}
public String next() {
int t = count;
count++;
return myclass.a[t];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
}
它似乎正在工作.
我應該有:
Myclass implements Iterable<Stirng>, Iterator<String> {
}
或者我應該把 MyClassIterator
放在 MyClass
之外
Or I should put MyClassIterator
outside MyClass
as
class MyClass implements Iterable<String> {
public String[] a = null;
public MyClass(String[] arr) {
a = arr;
}
public MyClassIterator iterator() {
return new MyClassIterator(this);
}
}
public class MyClassIterator implements Iterator<String> {
private MyClass myclass = null;
private int count = 0;
public MyClassIterator(MyClass m) {
myclass = m;
}
public boolean hasNext() {
return count < myclass.a.length;
}
public String next() {
int t = count;
count++;
return myclass.a[t];
}
public void remove() {
throw new UnsupportedOperationException();
}
}
哪個更好?
推薦答案
你應該幾乎永遠同時實現 Iterable
和 Iterator
班級.他們做不同的事情.迭代器自然是有狀態的 - 當您使用它進行迭代時,它必須更新其對世界的看法.然而,一個可迭代對象只需要能夠創建新的迭代器.特別是,您可以讓多個迭代器同時處理同一個原始可迭代對象.
You should almost never implement both Iterable
and Iterator
in the same class. They do different things. An iterator is naturally stateful - as you iterate using it, it has to update its view of the world. An iterable, however, only needs to be able to create new iterators. In particular, you could have several iterators working over the same original iterable at the same time.
您當前的方法非常好 - 我會更改實施的某些方面,但在職責分離方面很好.
Your current approach is pretty much okay - there are aspects of the implementation I'd change, but it's fine in terms of the separation of responsibilities.
這篇關于在同一個類中實現 Java Iterator 和 Iterable?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!