输出顺序请老师指导一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class StudentTest { public static void main(String[] args) { //定义三个Student类的对象及一个HashSet类的对象 Student stu1= new Student( 3 , "William" , 65 .0f); Student stu2= new Student( 1 , "Tom" , 87 .0f); Student stu3= new Student( 2 , "Lucy" , 95 .0f); //System.out.println(stu1); //将Student类的对象添加到集合中 Set set= new HashSet(); set.add(stu3); set.add(stu2); set.add(stu1); //使用迭代器显示Student类的对象中的内容 Iterator it=set.iterator(); while (it.hasNext()){ System.out.println(it.next()); } System.out.println( "插入重复数据后:" ); //插入重复数据 Student stu4= new Student( 2 , "Lucy" , 95 .0f); set.add(stu4); //使用迭代器显示Student类的对象中的内容 it=set.iterator(); while (it.hasNext()){ System.out.println(it.next()); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 | public class Student{ //根据需求完成Student类的定义 private int stuId; private String name; private float score; public Student( int stuId,String name, float score){ this .setStuId(stuId); this .setName(name); this .setScore(score); } public int getStuId(){ return stuId; } public void setStuId( int stuId){ this .stuId=stuId; } public String getName(){ return name; } public void setName(String name){ this .name=name; } public float getScore(){ return score; } public void setScore( float score){ this .score=score; } public String toString(){ return "[学号:" + this .getStuId()+ ",姓名:" + this .getName()+ ",成绩:" + this .getScore()+ "]" ; } //重写hashCode方法 @Override public int hashCode() { final int prime = 31 ; int result = 1 ; result = prime * result + ((name == null ) ? 0 : name.hashCode()); result = prime * result + Float.floatToIntBits(score); result = prime * result + stuId; return result; } @Override public boolean equals(Object obj) { //判断对象是否相等,相等则返回true,不用继续比较属性了 if ( this ==obj) return true ; //判断obj是否是Student类的对象 if (obj.getClass()==Student. class ){ Student stu=(Student) obj; return (stu.getStuId()==stuId)&&stu.getName().equals(name)&&(stu.getScore()==score); } return true ; } } |
老师,为啥我这怎么改,输出顺序都是2 1 3,改了插入集合的顺序也还是213
1
收起
正在回答
1回答
同学你好,HashSet的无序是指不会记录插入的顺序,
但是HashSet存值的时候会根据hashCode()来计算存储的位置;也就是说,首先会计算对象hashcode值,根据hashcode的值输出集合,而每次计算的对象hashcode值都是相同的,所以每次输出顺序都是213.
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧