import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Iterator;
import java.util.List;
import javax.management.RuntimeErrorException;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Integer> arrayList = new ArrayList<Integer>();
// TODO Auto-generated method stub
List<Integer> arrayList = new ArrayList<Integer>();
for(int i = 0; i < 100 ; i++){
arrayList.add(new Integer((int) (Math.random() * 1000)));
}
arrayList.add(new Integer((int) (Math.random() * 1000)));
}
System.out.println("迭代器输出结果:");
Iterator<Integer> iterator = arrayList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().intValue());
}
Iterator<Integer> iterator = arrayList.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next().intValue());
}
try {
System.out.print("调用get()读取索引位置为50的元素:");
System.out.println(arrayList.get(50));
System.out.print("调用get()读取索引位置为102的元素:");
System.out.println(arrayList.get(102));
} catch (IndexOutOfBoundsException e) {
// TODO Auto-generated catch block
System.out.println("数组越界了");
e.printStackTrace();
}
}
System.out.print("调用get()读取索引位置为50的元素:");
System.out.println(arrayList.get(50));
System.out.print("调用get()读取索引位置为102的元素:");
System.out.println(arrayList.get(102));
} catch (IndexOutOfBoundsException e) {
// TODO Auto-generated catch block
System.out.println("数组越界了");
e.printStackTrace();
}
}
}
本文通过一个具体的Java代码示例展示了如何使用ArrayList来存储随机整数,并利用迭代器遍历输出这些元素。此外,还演示了如何通过索引访问特定元素,并处理可能出现的数组越界异常。
3022

被折叠的 条评论
为什么被折叠?



