使用接口List的get(int index)方法可以实现对列表的遍历。
示例:创建Student对象,包含Name和Age两个属性。然后创建一个集合用于存储Student的对象。然后遍历集合,输出集合对象。
/*创建Student类*/
public
class
Student {
private
String
name
;
private
int
age
;
public
Student() {
super
();
//
TODO
Auto-generated constructor stub
}
public
Student(String name,
int
age) {
super
();
this
.
name
= name;
this
.
age
= age;
}
public
String getName() {
return
name
;
}
public
void
setName(String name) {
this
.
name
= name;
}
public
int
getAge() {
return
age
;
}
public
void
setAge(
int
age) {
this
.
age
= age;
}
@Override
public
String toString() {
return
"Student [name="
+
name
+
", age="
+
age
+
"]"
;
}
}
/*
创建列表、遍历列表、输出结果
*/
import
java.util.ArrayList;
import
java.util.Iterator;
import
java.util.List;
public
class
ListDemo {
public
static
void
main(String[] args) {
// 创建列表对象
List list =
new
ArrayList();
// 创建元素对象
Student s1 =
new
Student(
"AAAA"
, 20);
Student s2 =
new
Student(
"BBBB"
, 22);
Student s3 =
new
Student(
"CCCC"
, 25);
Student s4 =
new
Student(
"DDDD"
, 29);
// 为集合添加对象
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
/* 遍历集合 */
// 方法一、通过Object[]数组进行遍历
Object[] obj = list.toArray();
for
(
int
i = 0; i < obj.
length
; i++) {
Student stu = (Student) obj[i];
System.
out
.println(stu);
}
System.
out
.println(
"-----------------------"
);
// 方法二、通过iteration迭代器遍历
Iterator it = list.iterator();
while
(it.hasNext()) {
System.
out
.println(it.next());
}
System.
out
.println(
"-----------------------"
);
// 方法三、通过List的get方法对集合进行遍历
int
size = list.size();
for
(
int
i = 0; i < size; i++) {
System.
out
.println(list.get(i));
}
}
}
输出结果:
Student [name=AAAA, age=20]
Student [name=BBBB, age=22]
Student [name=CCCC, age=25]
Student [name=DDDD, age=29]
-----------------------
Student [name=AAAA, age=20]
Student [name=BBBB, age=22]
Student [name=CCCC, age=25]
Student [name=DDDD, age=29]
-----------------------
Student [name=AAAA, age=20]
Student [name=BBBB, age=22]
Student [name=CCCC, age=25]
Student [name=DDDD, age=29]