黑马程序员------集合的遍历Iterator/ListIterator

本文详细介绍了Java中集合遍历的基本原理及实现方式,重点讲解了如何使用Iterator接口及其子接口ListIterator进行集合元素的遍历,展示了具体的代码示例,并解释了避免并发修改异常的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

                                                                               ------ 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);
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值