重写来equals后添加重复数据到集合中还是有问题
这是重写的Student中的equals方法
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj.getClass() == Student.class) {
Student stu = (Student) obj;
return stu.getName().equals(name) && stu.getStuId() == stuId;
}
return false;
}
当我添加了一个学好和姓名相同但是成绩不同的数据到set中,并没有被定义成重复的,而是添加进去了
Student s4 = new Student(3,"William",70);
set.add(s4);
it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
正在回答 回答被采纳积分+1
public class Student {
private int stuId;
private String name;
private float score;
public Student(int stuId, String name, float score) {
super();
this.setName(name);
this.setScore(score);
this.setStuId(stuId);
}
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 stu = (Student) obj;
return stu.getName().equals(name) && stu.getStuId() == stuId;
}
return false;
}
}
下面是测试类
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
public class Test{
public static void main(String[] args){
Student s1 = new Student(1,"Tom",87);
Student s2 = new Student(2,"Lucy",95);
Student s3 = new Student(3,"William",65);
HashSet set = new HashSet();
set.add(s1);
set.add(s2);
set.add(s3);
Iterator it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
System.out.println("---------------------");
Student s4 = new Student(3,"William",65);
set.add(s4);
it = set.iterator();
while(it.hasNext()){
System.out.println(it.next());
}
}
}
好像复制过来格式不对。
- 参与学习 人
- 提交作业 7317 份
- 解答问题 14452 个
想要入门学编程?多年一直活跃在编程语言排行版前列的Java是一个很好的选择。本路径将从Java基础语法、面向对象、常用工具类三部分,为你开启软件开发的大门!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星