如何使用自定义类为每个循环使用 java?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/975383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use the java for each loop with custom classes?
提问by Geo
I think most coders have used code like the following :
我认为大多数编码员都使用过如下代码:
ArrayList<String> myStringList = getStringList();
for(String str : myStringList)
{
doSomethingWith(str);
}
How can I take advantage of the for each loop with my own classes? Is there an interface I should be implementing?
如何在我自己的类中利用 for each 循环?是否有我应该实现的接口?
采纳答案by Brian Agnew
回答by Pierre
回答by Tombart
The short version of for loop (T
stands for my custom type):
for 循环的简短版本(T
代表我的自定义类型):
for (T var : coll) {
//body of the loop
}
is translated into:
被翻译成:
for (Iterator<T> iter = coll.iterator(); iter.hasNext(); ) {
T var = iter.next();
//body of the loop
}
and the Iterator for my collection might look like this:
我的集合的迭代器可能如下所示:
class MyCollection<T> implements Iterable<T> {
public int size() { /*... */ }
public T get(int i) { /*... */ }
public Iterator<T> iterator() {
return new MyIterator();
}
class MyIterator implements Iterator<T> {
private int index = 0;
public boolean hasNext() {
return index < size();
}
public type next() {
return get(index++);
}
public void remove() {
throw new UnsupportedOperationException("not supported yet");
}
}
}