打印名字,年龄,性别
package
com;
public
class
Student {
private
int
id
;
private
String
name
;
private
String
sex
;
public
Student(
int
id
, String
name
, String
sex
) {
super
();
this
.
id
=
id
;
this
.
name
=
name
;
this
.
sex
=
sex
;
}
public
int
getId() {
return
id
;
}
public
void
setId(
int
id
) {
this
.
id
=
id
;
}
public
String getName() {
return
name
;
}
public
void
setName(String
name
) {
this
.
name
=
name
;
}
public
String getSex() {
return
sex
;
}
public
void
setSex(String
sex
) {
this
.
sex
=
sex
;
}
@Override
public
String toString() {
return
"Student [id="
+
id
+
", name="
+
name
+
", sex="
+
sex
+
"]"
;
}
}
Student类
package
com;
import
java.util.ArrayList;
import
java.util.List;
public
class
ListTest {
public
static
void
main(String[]
args
) {
List<Student>
list
=
new
ArrayList<Student>();
list
.add(
new
Student(1,
"亚托克斯"
,
"男"
));
list
.add(
new
Student(2,
"亚索"
,
"男"
));
list
.add(
new
Student(3,
"亚当"
,
"男"
));
list
.add(
new
Student(4,
"亚洲人"
,
"男"
));
list
.add(
new
Student(5,
"亚瑟"
,
"男"
));
//移除元素
list
.remove(4);
//替换元素
list
.set(0,
new
Student(5,
"亚麻跌"
,
"男"
));
//遍历方式
for
(
int
i
= 0;
i
<
list
.size();
i
++) {
//根据下标,返回指定下标的元素
Student
s
=
list
.get(
i
);
System.
out
.println(
s
.getId()+
" "
+
s
.getName()+
" "
+
s
.getSex());
System.
out
.println(
s
);
}
}
}
第二种
System.
out
.println(
"======================================"
);
//迭代器方式
Iterator<Student>
it
=
list
.iterator();
while
(
it
.hasNext()){
//判断是否右下一个元素
//去除下一个元素
Student
s
=
it
.next();
System.
out
.println(
s
);
}
第3种
System.
out
.println(
"======================================"
);
//第3中
foreach
for
(Student
student
:
list
) {
System.
out
.println(
student
);
}