Java任务--数组迭代器

来源:互联网 发布:济南软件的公司 编辑:程序博客网 时间:2024/05/20 03:42
使用ArrayList集合,对其添加100个不同的元素:
1.使用add()方法将元素添加到ArrayList集合对象中;
2.调用集合的iterator()方法获得Iterator对象,并调用Iterator的hasNext()和next()方法,迭代的读取集合中的每个元素;

3.调用get()方法先后读取索引位置为50和102的元素,要求使用try-catch结构处理下标越界异常;

import java.util.ArrayList;import java.util.Iterator;public class ArrayExamply {public static void main(String[] args) {ArrayList array = new ArrayList();System.out.println("打印数组中的所有元素:");for(int i=0;i<100;i++){array.add(i);}Iterator it = array.iterator();//为数据添加迭代器while(it.hasNext()){   //只要迭代器还有数据存在就输出System.out.println(it.next());}try{   //用try-catch捕获数组越界异常System.out.println("读取索引位置为50的元素:");System.out.println(array.get(50)); //用get方法获得某个位序的的数据System.out.println("读取索引位置为102的元素:");System.out.println(array.get(102));}catch(IndexOutOfBoundsException e){System.out.println("数组越界了");//否则捕获异常输出}}}
运行结果: