要求:
一.使用泛型版的ArrayList集合,对其添加100个不同的整数:
1.使用add()方法将100个整数添加到ArrayList集合中;
2.调用集合的iterator()方法获得Iterator器,并调用Iterator的hasNext()和next()方法,迭代的读取集合中的每个整数并输出;
一.使用泛型版的ArrayList集合,对其添加100个不同的整数:
1.使用add()方法将100个整数添加到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<num> list=new ArrayList<num>();
//通过for循环语句,向集合中添加num对象
for(int i=0;i<100;i++) {
list.add(new num(i));
}
Iterator<num> it=list.iterator();
while(it.hasNext()) {
num nu=it.next();
System.out.println(nu.m);
}
try {
//读取索引位置为50的元素(list.get(50)读取到的是num对象,)
//通过list.get(50).m 获取int型m的值
System.out.println(list.get(50).m);
//读取索引位置为102的元素
System.out.println(list.get(102).m);
}catch(IndexOutOfBoundsException e){
System.out.println("下标越界异常");
}
}
}
public class num {
int m;
num(int n){
m=n;
}
}
(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
下标越界异常