为什么最后遍历出来的是所有的课程
package com.collection.map;
import java.util.List;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class SetTest {
public List<Course> coursesToSelect;
public SetTest() {
coursesToSelect = new ArrayList<Course>();//构造器中初始化备选课程
}
public void testAdd() {
System.out.println("有如下课程待选:");
Course cr1 = new Course("1","数据结构");
coursesToSelect.add(cr1);
Course cr2 = new Course("2","c语言");
coursesToSelect.add(0,cr2);
Course[] course = {new Course("3","离散数学"),new Course("4","汇编语言")};
coursesToSelect.addAll(Arrays.asList(course));
Course[] course2 = {new Course("5","高等数学"),new Course("6","大学英语")};
coursesToSelect.addAll(2,Arrays.asList(course2));
}
/**
* 循环遍历一下
* @param args
*/
public void testForEach() {
for(Object obj : coursesToSelect) {
Course cr = (Course)obj;
System.out.println("课程 :"+cr.id + ":" + cr.name);
}
}
public static void main(String[] args) {
SetTest st = new SetTest();
st.testAdd();
st.testForEach();
//创建一个学生对象
Student student = new Student("1","小明");
System.out.println("欢迎学生 :"+student.name+"选课");
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.courses.add(cr);
}
}
}
st.testForEachForSet(student);
}
//新建一个方法遍历学生所选课程
public void testForEachForSet(Student student) {
for(Course cr:student.courses) {
System.out.println("选择了课程 : "+cr.id+":"+cr.name);
}
}
}