Java基础知识强化之集合框架笔记06:Collection集合存储自定义对象并遍历的案例

1.练习:用集合存储5个学生对象,并把学生对象进行遍历。

分析:

(1)创建学生类
(2)创建集合对象
(3)创建学生对象
(4)把学生添加到集合
(5)把集合转成数组
(6)遍历数组

2. 代码示例:

Student.java如下

 1 package cn.itcast_02;
 2 
 3 public class Student {
 4     // 成员变量
 5     private String name;
 6     private int age;
 7 
 8     // 构造方法
 9     public Student() {
10         super();
11     }
12 
13     public Student(String name, int age) {
14         super();
15         this.name = name;
16         this.age = age;
17     }
18 
19     // 成员方法
20     // getXxx()/setXxx()
21     public String getName() {
22         return name;
23     }
24 
25     public void setName(String name) {
26         this.name = name;
27     }
28 
29     public int getAge() {
30         return age;
31     }
32 
33     public void setAge(int age) {
34         this.age = age;
35     }
36 }

同时StudentDemo.java如下:

 1 package cn.itcast_02;
 2 
 3 import java.util.ArrayList;
 4 import java.util.Collection;
 5 
 6 /*
 7  * 练习:用集合存储5个学生对象,并把学生对象进行遍历。
 8  * 
 9  * 分析:
10  * A:创建学生类
11  * B:创建集合对象
12  * C:创建学生对象
13  * D:把学生添加到集合
14  * E:把集合转成数组
15  * F:遍历数组
16  */
17 public class StudentDemo {
18     public static void main(String[] args) {
19         // 创建集合对象
20         Collection c = new ArrayList();
21 
22         // 创建学生对象
23         Student s1 = new Student("林青霞", 27);
24         Student s2 = new Student("风清扬", 30);
25         Student s3 = new Student("令狐冲", 33);
26         Student s4 = new Student("武鑫", 25);
27         Student s5 = new Student("刘晓曲", 22);
28 
29         // 把学生添加到集合
30         c.add(s1);
31         c.add(s2);
32         c.add(s3);
33         c.add(s4);
34         c.add(s5);
35 
36         // 把集合转成数组
37         Object[] objs = c.toArray();
38         // 遍历数组
39         for (int x = 0; x < objs.length; x++) {
40             // System.out.println(objs[x]);
41 
42             Student s = (Student) objs[x];
43             System.out.println(s.getName() + "---" + s.getAge());
44         }
45     }
46 }

运行效果如下:

原文地址:https://www.cnblogs.com/hebao0514/p/4851467.html