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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值