Collection的实现——学生选课(二)

Posted on 2017-09-12 12:30  雾的鱼坂  阅读(90)  评论(0)    收藏  举报

创建ListTest类来作为备选课程类

public List coursesToselect; //用于存放备选课程List

public void testAdd()   //用于往coursesToselect添加备选课程

coursesToselect.add(cr1); //通过add方法往备选课程添加了Cr1课程

package xuanke;

import java.util.ArrayList;
import java.util.List;
/*
 * 备选课程类
 */
public class ListTest {
          /*
           * 用于存放备选课程List
           */
    public List coursesToselect;
    public ListTest() {
        this.coursesToselect=new ArrayList();
        //List是一个接口不能实例化,要引用ArrayLIst接口
    }
    /*
     * 用于往coursesToselect添加备选课程
     */
    public void testAdd() {
        Course cr1=new Course("1","数据结构"); 
        coursesToselect.add(cr1);
        //通过add方法往备选课程添加了Cr1课程
        Course  temp=(Course) coursesToselect.get(0);
        //get(0)起始位置是0
        //对象存入集合都会变成Object类型,需要进行类型转换
        System.out.println("添加了课程:"+temp.id+":"+temp.name);
    }
 public static void main(String[] args) {
    ListTest lt=new ListTest();
    lt.testAdd();
}
}

运行结果:

添加乐课程:1:数据结构