使用ArrayList集合,对其添加100个不同的元素:
1.使用add()方法将元素添加到ArrayList集合对象中;
2.调用集合的iterator()方法获得Iterator对象,并调用Iterator的hasNext()和next()方法,迭代的读取集合中的每个元素;
1.使用add()方法将元素添加到ArrayList集合对象中;
2.调用集合的iterator()方法获得Iterator对象,并调用Iterator的hasNext()和next()方法,迭代的读取集合中的每个元素;
3.调用get()方法先后读取索引位置为50和102的元素,要求使用try-catch结构处理下标越界异常;
(1)代码实现
import java.util.*;
public class Array {
public static void main(String[] args) {
//创建ArrayList集合
ArrayList list= new ArrayList();
//向集合list添加100个不同的元素
for(int i=0;i<100;i++) {
list.add(i);
}
//获取Iterator迭代器
Iterator it=list.iterator();
//判断下一个元素是否存在
while(it.hasNext()) {
//读取下一个元素
Object ob=it.next();
System.out.println(ob);
}
try {
//读取索引位置为50的元素
System.out.println(list.get(50));
//读取索引位置为102的元素
System.out.println(list.get(102));
}catch(IndexOutOfBoundsException e){
System.out.println("下标越界异常");
}
}
}
(2)运行结果
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
50
下标越界异常