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());
}
}
}0
收起
正在回答
1回答
同学代码没有错哦~程序正确呢。
重复添加学生信息本身就不会报错,只是在集合中会被覆盖,例如,在集合中重复添加第四个学生Willam,但集合中还是只有三个元素而已。
如果我的回答解决了你的疑惑,请采纳。祝:学习愉快~
1. Java 零基础入门
- 参与学习 人
- 提交作业 3802 份
- 解答问题 11489 个
本阶段带你迈入Java世界,学习Java必备基础知识,基础语法、面向对象思想以及常用工具类的使用。
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星