HashSet的for-each 和 iterator 的遍历为什么每次输出的顺序是一定的,不应该是无序的吗?

学生类:

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();

}

}

测试类:

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Iterator;

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(){

Course c1 = new Course("1","数据结构");

coursesToSelect.add(c1);

Course c2 = new Course("2","C语言");

coursesToSelect.add(1,c2);

Course[] c = {new Course("3","离散数学"),new Course("4","汇编语言")};

coursesToSelect.addAll(Arrays.asList(c));

}

public void testForEach(){

System.out.println("有如下课程可以选:");

for(Course c : coursesToSelect){

System.out.println("课程:"+c.id+":"+c.name);

}

}

public void testForEachForSet(Student stu){

for(Course c : stu.courses){

System.out.println("选择了课程:"+c.id+":"+c.name);

}

}

public void testIteratorForSet(Student stu){

Iterator<Course> it = stu.courses.iterator();

while(it.hasNext()){

Course c = it.next();

System.out.println("选择了课程:"+c.id+":"+c.name);

}

}

public static void main(String[] args) {

SetTest st = new SetTest();

st.testAdd();

st.testForEach();

Student stu = new Student("1","小明");

System.out.println("欢迎学生:"+stu.name+"选课!");

Scanner in = new Scanner(System.in);

for(int i=0;i<3;i++){

System.out.print("输入你想选择的课程:");

String choice = in.next();

for(Course c : st.coursesToSelect){

if(c.id.equals(choice)){

stu.courses.add(c);

}

}

}

st.testIteratorForSet(stu);

}


慕粉3291149
浏览 2407回答 2
2回答

慕仰7261054

无序是指它每次存进去的东西的存储地址不是按顺序排列的,但是当你存进去之后段时间内它的hash地址是不会变的

慕粉_编程新手

是根据你存储进去的顺序遍历的
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java