set添加重复学生信息没有报错?是我代码写错了吗?

set添加重复学生信息没有报错?是我代码写错了吗?

package com.imooc.set;
public class Student {
 private int id;
 private String name;
 private float score;
 public Student() {
 }
 public Student(int id, String name, float score) {
  this.id = id;
  this.name = name;
  this.score = score;
 }
 public int getId() {
  return id;
 }
 public void setId(int id) {
  this.id = id;
 }
 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() {
  String str = "[学号:" + id + ",姓名:" + name + ",成绩:" + score+"]";
  return str;
 }
 @Override
 public int hashCode() {
  final int prime = 31;
  int result = 1;
  result = prime * result + id;
  result = prime * result + ((name == null) ? 0 : name.hashCode());
  result = prime * result + Float.floatToIntBits(score);
  return result;
 }
 @Override
 public boolean equals(Object obj) {
  if (this == obj)
   return true;
  if (obj == null)
   return false;
  if (getClass() != obj.getClass())
   return false;
  Student other = (Student) obj;
  if (id != other.id)
   return false;
  if (name == null) {
   if (other.name != null)
    return false;
  } else if (!name.equals(other.name))
   return false;
  if (Float.floatToIntBits(score) != Float.floatToIntBits(other.score))
   return false;
  return true;
 }
}
package com.imooc.set;
import java.util.HashSet;
import java.util.Iterator;
public class StudentTest {
 public static void main(String[] args) {
 Student one=new Student(3,"William",65.0f);
 Student two=new Student(1,"Tom",87.0f);
 Student three=new Student(2,"Lucy",95.0f);
 HashSet<Student> hashset=new HashSet<Student>();
 hashset.add(one);
 hashset.add(two);
 hashset.add(three);
 //显示学生信息
 Iterator<Student> it = hashset.iterator();
 while (it.hasNext()) {
  System.out.println(it.next());
 }
 //添加一個重複信息
 Student four=new Student(3,"William",65.0f);
 hashset.add(four);
 System.out.println("**********************************");
 System.out.println("添加重复数据后的学生信息:");
 it=hashset.iterator();
 while (it.hasNext()) {
  System.out.println(it.next());
 }
 }
}


正在回答

登陆购买课程后可参与讨论,去登陆

1回答

同学代码没有错哦~程序正确呢。

重复添加学生信息本身就不会报错,只是在集合中会被覆盖,例如,在集合中重复添加第四个学生Willam,但集合中还是只有三个元素而已。

如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~

问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师