3-9编程
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 | package com.set; import java.util.HashSet; import java.util.Iterator; import java.util.Set; public class StudentTest { public static void main(String[] args) { // 定义三个Student类的对象及一个HashSet类的对象 Student st1 = new Student( 1 , "Tom" , 87 ); Student st2 = new Student( 2 , "Lucy" , 95 ); Student st3 = new Student( 3 , "William" , 65 ); Set set = new HashSet(); // 将Student类的对象添加到集合中 set.add(st1); set.add(st2); set.add(st3); // 使用迭代器显示Student类的对象中的内容 Iterator it = set.iterator(); while (it.hasNext()) { System.out.println(it.next()); // 添加一个重复数据到set中 Student st11 = new Student( 2 , "Lucy" , 95 ); set.add(st11); 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 67 68 69 70 71 | package com.set; public class Student { // 根据需求完成Student类的定义 private int stuId; private String name; private float score; public Student() { } public Student( int stuId, String name, float score) { super (); this .stuId = stuId; this .name = name; this .score = 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; } @Override public String toString() { return "[学号:" + stuId + ", 姓名:" + name + ", 成绩:" + score + "]" ; } @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) { if ( this ==obj) return true ; if (obj.getClass()==Student. class ) { Student student = (Student) obj; return (student.getStuId()==stuId)&&(student.getName().equals(name)&&(student.getScore()==score)); } return false ; } } |
为什么重复数据不管写什么都出来一个Tom
34
收起
正在回答
1回答
程序中交叉循环太多,边输出边添加,也有数据输出的与实际不符。注意以上图中的红框处要注释掉。你是想问Lucy添加了多次为什么只会输出一次吧,那是因为你重写了equals。这两个对像是相等的,所以在Set中只会存在一个
Java零基础入门18
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧