Java泛型-实现可迭代的接口
时间:2020-01-09 10:36:00 来源:igfitidea点击:
可以在新的for循环中使用我们自己的集合类型类。为此,类必须实现java.lang.Iterable <E>接口。这是一个非常基本的示例:
public class MyCollection<E> implements Iterable<E>{
public Iterator<E> iterator() {
return new MyIterator<E>();
}
}
这是MyIterator类的相应实现框架:
public class MyIterator <T> implements Iterator<T> {
public boolean hasNext() {
//implement...
}
public T next() {
//implement...;
}
public void remove() {
//implement... if supported.
}
}
这是如何使用生成的MyCollection以及新的for循环:
public static void main(String[] args) {
MyCollection<String> stringCollection = new MyCollection<String>();
for(String string : stringCollection){
}
}

