使用set'集做练习时,运行结果更像是栈
package com.imooc.collection; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Scanner; public class SetTest { public List<Course> coursesToSelect; public SetTest(){ coursesToSelect = new ArrayList<Course>(); } public void add(){ Course cr1 = new Course("1", "数据结构"); coursesToSelect.add(cr1); Course temp = (Course) coursesToSelect.get(0); //System.out.println("课程id:"+temp.id+"课程名字:"+temp.name); Course cr2 = new Course("2", "C++"); coursesToSelect.add(0, cr2); Course temp2 = (Course) coursesToSelect.get(0); //System.out.println("课程id:"+temp2.id+"课程名字:"+temp2.name); //以下方法会抛出数组下标越界异常 /*Course cr3 = new Course("3", "java"); coursesToSelect.add(3, cr3);*/ Course[] course = {new Course("3", "离散数学"), new Course("4", "汇编语言")}; coursesToSelect.addAll(Arrays.asList(course)); Course temp3 = (Course) coursesToSelect.get(2); Course temp4 = (Course) coursesToSelect.get(3); // System.out.println("添加了两门课程:" + temp3.id + ":" + // temp3.name + ";" + temp4.id + ":" + temp4.name); Course[] course1 = {new Course("5", "高等数学"), new Course("6", "大学英语")}; coursesToSelect.addAll(2, Arrays.asList(course1)); Course temp5 = (Course) coursesToSelect.get(2); Course temp6 = (Course) coursesToSelect.get(3); // System.out.println("添加了两门课程:" + temp5.id + ":" + // temp5.name + ";" + temp6.id + ":" + temp6.name); } public void TestGet(){ int size = coursesToSelect.size(); System.out.println("有如下课程待选:"); for(int i = 0; i < size; i++){ Course cr = (Course) coursesToSelect.get(i); System.out.println("课程:"+cr.id+":"+cr.name); } } public void TestForeach(){ for(Object obj : coursesToSelect){ Course cr = (Course) obj; System.out.println("课程:"+cr.id+":"+cr.name); } } public static void main(String[] args) { // TODO Auto-generated method stub SetTest st = new SetTest(); st.add(); st.TestForeach(); Student sd = new Student("1", "小明"); System.out.println("欢迎"+sd.name+"选课!"); Scanner sc = new Scanner(System.in); for (int i = 0; i < 3; i++) { System.out.println("请输入课程ID:"); String courseId = sc.next(); for (Course cr : st.coursesToSelect) { if(cr.id.equals(courseId)) { sd.courses.add(cr); sd.courses.add(cr); } } } st.forEachCourse(sd); } public void forEachCourse(Student sd){ for (Course cr : sd.courses ) { System.out.println(sd.name+"选的课程为:"+cr.id+cr.name); } } } package com.imooc.collection; /* * */ public class Course { public String id; public String name; public Course(String id, String name) { this.id = id; this.name = name; } } package com.imooc.collection; import java.util.HashSet; import java.util.Set; /* * 学生类 */ public class Student { public String id; public String name; public Set<Course> courses; public Student(String id, String name){ this.id = id; this.name = name; this.courses = new HashSet<Course>(); } }
我的感觉更像是栈,求解是怎么回事,最后输入的最先输出,重新执行还是这样子
有如下课程待选:
课程:2:C++
课程:1:数据结构
课程:5:高等数学
课程:6:大学英语
课程:3:离散数学
课程:4:汇编语言
欢迎小明选课!
请输入课程ID:
1
请输入课程ID:
2
请输入课程ID:
3
小明选的课程为:3离散数学
小明选的课程为:2C++
小明选的课程为:1数据结构