zoukankan      html  css  js  c++  java
  • Collection的实现——学生选课(六)

    应用泛型管理课程

    首先创建泛型Course的List属性并初始化

    public List<Course>courses;  

    public testGenneric() {
    this.courses=new ArrayList<Course>();
    //带有泛型的List属性的courses实例化完成
    }

       public void testAdd() {
           Course cr=new Course("1","大学英语");
           courses.add(cr);
           // 泛型类型不能添加规定类型以外的对象,否则会报错
         // courses.add("能否添加一些奇怪的东西呢?")
           Course cr1=new Course("2","大学语文");
           courses.add(cr1);
       }
       /*
        * 泛型集合可以添加泛型的子类对象的实例
        */
       public void testChild() {
           childCourse ccr=new childCourse();
           ccr.id="3";
           ccr.name="我是子类对象的实例";
           courses.add(ccr);
       }

    需要注意的是:泛型不能使用基本类型,只能使用其包装类

    学生选课

     //创建学生对象
             Student student =new Student("1","小明");
             System.out.println("欢迎学生"+student.name+"选课");
             //创建 一个Scanner对象用来接收从键盘输入的课程ID
             Scanner console=new Scanner(System.in);
             
             for(int i=0;i<3;i++)
             {System.out.println("请输入课程ID");
             String courseId=console.next();
                 for(Course cr :st.coursesToselect) {
                     if(cr.id.equals(courseId)) {
                         student.course.add(cr); //往student的course中添加cr对象
                        /* Set中无论添加多少次相同对象,最终只会保留第一个添加的对象
                         *  student.course.add(cr);
                         */
                         
                     }
                 }
             }

    通过ForEach循环遍历输出学生所选的课程信息

     public  void tsetForEachForSet(Student student) {
                  /*
                 * 打印输出学生所选的课程
                 */
                System.out.println("共选择了:"+student.course.size()+"门课程");
               for(Course cr :student.course) {
                   System.out.println("选择了课程"+cr.id+":"+cr.name);
               
    
           }
            }

     需要注意的是: 循环遍历Set中的元素只能用ForEach或Iterator方法,不能调用get方法,因为Set是无序的

  • 相关阅读:
    洛谷 P1057 传球游戏
    BZOJ 1801: [Ahoi2009]chess 中国象棋
    BZOJ 1806: [Ioi2007]Miners 矿工配餐
    51nod 1276 岛屿的数量
    BZOJ 1800: [Ahoi2009]fly 飞行棋
    路由控制和视图层
    django的零碎注意点
    Django框架简介
    Bootstrap框架
    jQuery基础知识
  • 原文地址:https://www.cnblogs.com/ljp-yuban/p/7590808.html
Copyright © 2011-2022 走看看