hashCode()和equals()只对学号和名字判断,还能输入重复数据。请老师帮忙
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 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 | import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class StudentTest { public static void main(String[] args) { //定义三个Student类的对象及一个HashSet类的对象 Student s1= new Student( 1 , "Tom" , 87 ); Student s2= new Student( 2 , "Lucy" , 95 ); Student s3= new Student( 3 , "William" , 65 ); Set<Student> s= new HashSet<Student>(); //将Student类的对象添加到集合中 s.add(s1); s.add(s2); s.add(s3); //使用迭代器显示Student类的对象中的内容 Iterator<Student> it=s.iterator(); while (it.hasNext()){ System.out.println(it.next()); } System.out.println( "**************************************************" ); System.out.println( "插入学号名字重复数据:" ); Student s4= new Student( 1 , "GWA" , 100 ); //学号重复 Student s5= new Student( 5 , "Tom" , 90 ); //名字重复 s.add(s4); s.add(s5); it=s.iterator(); while (it.hasNext()){ System.out.println(it.next()); } } } //Student类 public class Student{ //根据需求完成Student类的定义 private int stuId; private String name; private float score; public Student( int stuId,String name, float score){ setStuId(stuId); setName(name); setScore(score); } public int getStuId(){ return this .stuId; } public void setStuId( int stuId){ this .stuId=stuId; } public String getName(){ return this .name; } public void setName(String name){ this .name=name; } public float getScore(){ return this .score; } public void setScore( float score){ this .score=score; } @Override public String toString(){ return "[学号:" + this .stuId+ ",姓名:" + this .name+ ",成绩:" + this .score+ "]" ; } //集合的源码Cat类中所讲 @Override public int hashCode(){ final int prime= 31 ; int result= 1 ; result=prime*result+stuId; result=prime*result+((name== null )? 0 :name.hashCode()); return result; } @Override public boolean equals(Object obj){ //判断对象是否相等 if ( this ==obj) return true ; if (obj.getClass()==Student. class ){ Student stu=(Student)obj; return (stu.getStuId()==stuId)&&(stu.getName().equals(name)); } return false ; } } |
0
收起
正在回答
2回答
如果之比较学号的话把下图红框部分去掉就可以了,意思是只有学号一致,就认为是重复的。名称同理。如果只判断名称,把学号的比较去掉就可以了
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧