添加重复数据
package com.imooc.test;
public class Student {
private String name;
private int stuld;
private float score;
public Student() {
}
public Student(String name, int stuld, float score) {
this.setName(name);
this.setStuld(stuld);
this.setScore(score);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getStuld() {
return stuld;
}
public void setStuld(int stuld) {
this.stuld = stuld;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + stuld;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj.getClass() == Student.class) {
Student student = (Student) obj;
return student.getStuld() == stuld && (student.getName().equals(name));
}
return false;
}
@Override
public String toString() {
return "[学号:" + this.getStuld() + ", 姓名:" + this.getName() + ", 成绩:" + this.getScore() + "]";
}
}
package com.imooc.test;
问题描述:
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class StudentTest {
public static void main(String[] args) {
// TODO 自动生成的方法存根
Student student3 = new Student("William", 3, 65.0f);
Student student1 = new Student("Tom", 1, 87.0f);
Student student2 = new Student("Lucy", 2, 95.0f);
Set<Student> set = new HashSet<Student>();
set.add(student1);
set.add(student2);
set.add(student3);
Iterator it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
System.out.println("=========================");
Student student4 = new Student("Lucy", 3, 954.0f);
Student student5 = new Student("William", 3, 65.0f);
set.add(student4);
set.add(student5);
it = set.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
}
}
问题描述:
这个判断是否重复是当学号和姓名都重复时才进行判定重复,单独判断学号或者姓名重复怎么写
22
收起
正在回答
1回答
同学你好,
1、是的,理解是正确的
2、这里只需要对equals()和hashCode()方法进行删减即可,如下举例:判断姓名
祝学习愉快~
java工程师2020版
- 参与学习 人
- 提交作业 9393 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星