Iterator
- Iterator 是一个接口,如要使用,必须依靠 Collection 接口中定义的方法:public Iterator<> iterator();
1. API
类型 | 方法 | 说明 |
---|
boolean | hasNext() | 用来判断集合中是否有下一个元素可以迭代 |
E | next() | 用来返回迭代的下一个元素,并把指针向后移动一位 |
void | remove() | 删除上一次使用 next() 调用的元素,必须先用 next,再使用 romove,如果先用 remove 方法会出现 IllegalStateException 异常 |
2. 常用方法
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class test {
public static void main(String[] args) {
Collection<String> coll = new ArrayList();
coll.add("apple");
coll.add("banana");
System.out.println(coll.size());
ArrayList array = new ArrayList();
array.add("cat");
array.add("dog");
if (!array.isEmpty()) {
coll.addAll(array);
}
System.out.println(coll.size());
Iterator<String> it = coll.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
if (coll.contains("Cat")) {
System.out.print("coll has cat.");
}
coll.removeAll(array);
it = coll.iterator();
while (it.hasNext()) {
System.out.print(it.next() + " ");
}
System.out.println();
Object[] str = coll.toArray();
String s = "";
System.out.print("elements in coll: ");
for (int i = 0; i < str.length; i++) {
s = (String) str[i];
System.out.print(s + " ");
}
}
}