package com.imooc.collection; import java.util.HashSet; import java.util.Set; /** * 学生类 * * @author sama * */ public class Student { private String id; private String name; private Set<Course> courses; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Set<Course> getCourses() { return courses; } public void setCourses(Set<Course> courses) { this.courses = courses; } public Student(String id, String name) { this.id = id; this.name = name; this.courses = new HashSet<Course>(); } }
package com.imooc.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.Set; public class SetTest { private List<Course> coursesToSelect; public List<Course> getCoursesToselect() { return coursesToSelect; } public void setCoursesToselect(List<Course> coursesToselect) { this.coursesToSelect = coursesToselect; } public SetTest() { this.coursesToSelect = new ArrayList<Course>(); } public void testAdd() {// 创建一个课程对象,并通过调用add方法,添加到备选课程List中 Course cr1 = new Course("1", "数据结构"); coursesToSelect.add(cr1); Course cr2 = new Course("2", "C语言"); coursesToSelect.add(0, cr2); Course[] courses = { new Course("3", "离散数学"), new Course("4", "汇编语言") }; coursesToSelect.addAll(Arrays.asList(courses)); Course[] courses2 = { new Course("5", "高等数学"), new Course("6", "大学英语") }; coursesToSelect.addAll(2, Arrays.asList(courses2)); } /* * 通过for each方法访问集合元素 */ public void teatForEach() { System.out.println("有如下课程待选(通过foreach方法遍历):"); for (Course cr : coursesToSelect) { System.out.println("课程:" + cr.getId() + ":" + cr.getName()); } } @SuppressWarnings("unchecked") public static void main(String[] args) { SetTest st = new SetTest(); st.testAdd(); st.teatForEach(); // 创建一个新的学生对象 Student student = new Student("1", "小明"); System.out.println("欢迎学生:" + student.getId() + ":" + student.getName()); // 创建一个Scanner对象,用来接收从键盘输入的课程ID Scanner input = new Scanner(System.in); for (int i = 0; i < 3; i++) { System.out.println("请输入课程ID:"); String courseId = input.next(); for (Course cr : st.coursesToSelect) { if ((cr.getId()).equals(courseId)) { student.setCourses((Set<Course>) cr); } } } st.testForEachSet(student); } public void testForEachSet(Student student) { for (Course cr : student.getCourses()) { System.out.println("选择了课程:" + cr.getId() + ":" + cr.getName()); } } }
我把课程代码部分的成员变量改为private,用geterseter方法修改和获取,但是运行的时候,输入课程ID就报错,好像是student.setCourses((Set<Course>) cr);这里类型转换错误。
你那个判断集合里面是否有同名ID的地方,应该是如果有就不执行并报错,没有才进行添加