zoukankan      html  css  js  c++  java
  • Java基础知识强化之集合框架笔记13:Collection集合存储学生对象并遍历

    1. Collection集合存储学生对象并遍历:

    需求:存储自定义对象并遍历Student(name,age)

      分析:
        (1)创建学生类
        (2)创建集合对象
        (3)创建学生对象
        (4)把学生对象添加到集合对象中
        (5)遍历集合

    2. 代码示例:

    Student.java,如下:

     1 package cn.itcast_04;
     2 
     3 public class Student {
     4     private String name;
     5     private int age;
     6 
     7     public Student() {
     8         super();
     9     }
    10 
    11     public Student(String name, int age) {
    12         super();
    13         this.name = name;
    14         this.age = age;
    15     }
    16 
    17     public String getName() {
    18         return name;
    19     }
    20 
    21     public void setName(String name) {
    22         this.name = name;
    23     }
    24 
    25     public int getAge() {
    26         return age;
    27     }
    28 
    29     public void setAge(int age) {
    30         this.age = age;
    31     }
    32 
    33 }

    再次编写一个测试类CollectionTest2,如下:

     1 package cn.itcast_04;
     2 
     3 import java.util.ArrayList;
     4 import java.util.Collection;
     5 import java.util.Iterator;
     6 
     7 /*
     8  * 需求:存储自定义对象并遍历Student(name,age)
     9  *
    10  * 分析:
    11  *         A:创建学生类
    12  *         B:创建集合对象
    13  *         C:创建学生对象
    14  *         D:把学生对象添加到集合对象中
    15  *         E:遍历集合
    16  */
    17 public class CollectionTest2 {
    18     public static void main(String[] args) {
    19         // 创建集合对象
    20         Collection c = new ArrayList();
    21 
    22         // 创建学生对象
    23         Student s1 = new Student("貂蝉", 25);
    24         Student s2 = new Student("小乔", 16);
    25         Student s3 = new Student("黄月英", 20);
    26         Student s4 = new Student();
    27         s4.setName("大乔");
    28         s4.setAge(26);
    29 
    30         // 把学生对象添加到集合对象中
    31         c.add(s1);
    32         c.add(s2);
    33         c.add(s3);
    34         c.add(s4);
    35         c.add(new Student("孙尚香", 18)); // 匿名对象
    36 
    37         // 遍历集合
    38         Iterator it = c.iterator();
    39         while (it.hasNext()) {
    40             Student s = (Student) it.next();
    41             System.out.println(s.getName() + "---" + s.getAge());
    42         }
    43     }
    44 }

    运行效果如下:

  • 相关阅读:
    4月22日:毕业设计计划
    4月21日:毕业设计计划
    4月11日:毕业设计计划
    4月9日:毕业设计计划
    4月8日:毕业设计计划
    4月2日:毕业设计计划
    4月1日:毕业设计计划
    3月31日:毕业设计计划
    3月30日:毕业设计计划
    3月28日:毕业设计计划
  • 原文地址:https://www.cnblogs.com/hebao0514/p/4851917.html
Copyright © 2011-2022 走看看