------
Java培训、Android培训、iOS培训、.Net培训、期待与您交流! -------
集合的遍历Iterator/ListIterator
迭代原理图
ListIterator是而特殊的迭代器,可以避免并发修改异常
遍历数组的方法,以及迭代器的代码构成package it.cast;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class CollectionTterator {
public static void main(String[] args) {
//创建集合对象
Collection collection = new ArrayList();
//创建学生对象
TestStudet testStudet1 = new TestStudet("张三", 23);
TestStudet testStudet2 = new TestStudet("李四", 24);
TestStudet testStudet3 = new TestStudet("王五", 25);
TestStudet testStudet4 = new TestStudet("赵六", 26);
//把学生对象放入集合当中
collection.add(testStudet1);
collection.add(testStudet2);
collection.add(testStudet3);
collection.add(testStudet4);
//遍历集合对象
//以前是创建对象数组,然后遍历数字得到结果
//现在利用Iterator遍历,格式如下
Iterator iterator = collection.iterator();
//判断有没有 元素
while (iterator.hasNext()) {
//不要多次使用next方法,那样会使输出返回异常
TestStudet testStudet =(TestStudet)iterator.next();
System.out.println(testStudet.getNameString()+"---"+testStudet.getAge());
}
}
}
迭代器代码构成原理public interface Inteator {
boolean hasNext();
3.这个接口里有这样的两个方法Object next();
}
public interface Iterable {
Iterator iterator(); 2.里面有个方法返回Iterator类型的方法
}
public interface Collection extends Iterable { 1. APi中有个父接口
Iterable在这里 Collection并没有对父类的方法进行实现,所以找他的子类看实现的方法
}
public interface List extends Collection {
Iterator iterator();
子类List也没有改写这个方法,但有继承关系,继续找子类的方法实现
}
public class ArrayList implements List {
在LIst的子类ArrayLIst找到了方法的重写public Iterator iterator() {
return new Itr();//返回一个对象,可以肯定Itr肯定是这个接口的实现类
}
//可以看到有一个内部类被Private修饰,只能自己看到
private class Itr implements Iterator {
public boolean hasNext() {}//同时在内部类中看到了这个接口的各种重写方法
public Object next(){}
}
}
Collection c = new ArrayList();
c.add("hello");
c.add("world");
c.add("java");
Iterator it = c.iterator(); //new Itr();
while(it.hasNext()) {
String s = (String)it.next();
System.out.println(s);
}