重写equals方法后,虽然不显示重复的元素了,但是查找还是能找到,为什么?
相关截图:
问题描述:
如果,s3和s4是相同元素,则应该只添加一个,另一个应该是查不到的状态啊,为什么在这里是可以查到的呢?
相关代码:
package com.demon.modle;
public class 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 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 "student [stuId=" + stuId + ", name=" + name + ", score=" + 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.getScore() == score && stu.getStuId() == stuId;
}
return false;
}
}
相关代码:
package com.demon.modle;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class test {
public static void main(String[] args) {
// TODO Auto-generated method stub
student s = new student(1,"张三",65);
student s2 = new student(2,"李四",87);
student s3 = new student(3,"王五",95);
student s4 = new student(3,"王五",95);
Set set = new HashSet();
set.add(s);
set.add(s2);
set.add(s3);
set.add(s4);
Iterator it = set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
System.out.println("添加重复元素后查找:");
if(set.contains(s4)) {
System.out.println("包含实例s4");
System.out.println(s4);
}else {
System.out.println("不包含");
System.out.println("s3:"+s3);
}
}
}
16
收起
正在回答 回答被采纳积分+1
1回答
java工程师2020版
- 参与学习 人
- 提交作业 9393 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星