输出顺序问题
输入的是2-1-4,输出就变为4-1-2了,
试了好多遍都是这个样子;
为什么?
package com.imooc.collection; import java.util.List; import java.util.ArrayList; import java.util.Arrays; import java.util.Scanner; public class SetTest { //创建带有泛型的List实例化对象,存放备选课程 public List<Course> coursesToSelect = new ArrayList<Course>(); /** *用于往coursesToSelect中添加课程的方法 */ public void testAdd(){ Course cr1 = new Course("1","数据结构"); coursesToSelect.add(cr1); Course temp = (Course)coursesToSelect.get(0); //System.out.println("添加了课程:" + temp.id +","+ temp.name); Course cr2 = new Course("2","C语言"); coursesToSelect.add(0,cr2); Course temp2 = (Course)coursesToSelect.get(0); //System.out.println("添加了课程:" + temp2.id + "," +temp2.name); // //重复添加课程1 // coursesToSelect.add(cr1); // Course temp0 = (Course)coursesToSelect.get(2); // System.out.println("添加了课程:" + temp0.id +","+ temp0.name); Course[] course = {new Course("3","离散数学"),new Course("4","汇编语言")}; coursesToSelect.addAll(Arrays.asList(course)); Course temp3 = (Course)coursesToSelect.get(3); //Course temp4 = (Course)coursesToSelect.get(4); //System.out.println("添加了两门课程:" + //temp3.id +"," + temp3.name + ";" + temp4.id + "," + temp4.name); Course[] course2 = {new Course("5","高等数学"),new Course("6","大学英语")}; coursesToSelect.addAll(2,Arrays.asList(course2)); Course temp5 = (Course)coursesToSelect.get(2); Course temp6 = (Course)coursesToSelect.get(3); //System.out.println("添加了两门课程:"+ // temp5.id + "," + temp5.name + ";" + temp6.id + "," +temp6.name); } /** * foreach循环遍历集合内元素,以显示课程 * @param args */ public void testForEach(){ System.out.println("有如下课程待选(通过for each访问):"); for(Course cr:coursesToSelect){ 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对象 Scanner input = new Scanner(System.in); /** * for循环3次获取所选课程 */ for(int i = 0;i < 3;i++){ System.out.println("请输入所选课程ID:"); String courseId = input.next(); //for each循环遍历coursesToSelect,找到对应课程 for(Course cr:st.coursesToSelect){ if(cr.id.equals(courseId)){ student.courses.add(cr); /** * Set中添加某个对象,无论添加多少次, * 最终只会保留第一次添加的对象的引用 */ //student.courses.add(cr); // student.courses.add(null); //可添加null但没什么意义 } } } st.testForEachForSet(student); } /** * for each循环 */ public void testForEachForSet(Student student){ //传递参数(此时好比没有main方法,故对象student还不存在) System.out.println("共选择了"+ student.courses.size() + "门课程!"); System.out.println("你选择的课程如下:"); for(Course cr : student.courses){ System.out.println(cr.id + "," +cr.name); //呃呃为啥总是输出固定的顺序(倒序)呢?? } } }