为什么遍历SET出来的是有序的,试了很多次都是这样
package com.study.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(){ this.coursesToSelect = new ArrayList<Course>(); } public void testAdd(){ //向List添加单个课程元素 Course cr1 = new Course("1","数据结构"); coursesToSelect.add(cr1); //向List中指定索引位置添加单个课程元素 Course cr2 = new Course("2", "C语言"); coursesToSelect.add(0, cr2); //用List的addAll方法添加多个课程元素 Course[] course = {new Course("3", "离散数学"),new Course("4", "汇编语言")}; //使用工具类Arrays的asList将数组转化为List元素 coursesToSelect.addAll(Arrays.asList(course)); //用List的addAll方法向List中的指定位置添加多个课程元素 Course[] course2 = {new Course("5", "高等数学"), new Course("6", "大学英语")}; coursesToSelect.addAll(2, Arrays.asList(course2)); } /** * 通过for each语名来遍历List中的元素,它是迭代器的简化写法 * @param argus */ 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 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 csr : student.courses){ System.out.println("选择了如下课程:" + csr.id + ":" + csr.name); } } }
遍历SET出来的是有序的,试了很多次都是这样。没有出现视频中的乱序
刚开始没贴出Student类,不好意思。Student.courses 是Set
package com.study.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>(); } }