请问该代码是否符合题目要求
相关代码:
package com.imooc.student;
public class Student {
//成员属性
private int stuld;
private String name;
private float score;
//无参构造
public Student() {
}
//带参构造
public Student(int stuld, String name, float score) {
super();
this.stuld = stuld;
this.name = name;
this.score = score;
}
//getter和setter
public int getStuld() {
return stuld;
}
public void setStuld(int stuld) {
this.stuld = stuld;
}
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;
}
//toString构造
@Override
public String toString() {
return " [学号:" + stuld + ", 姓名:" + name + ", 成绩:" + score + "]";
}
//has code和equals
@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 + stuld;
return result;
}
@Override
public boolean equals(Object obj) {
//判断对象是否相等
if(this==obj)
return true;
//判断obj是否是Student类的对象
if(obj.getClass()==Student.class) {
Student student=(Student)obj;
return student.getName().equals(name)&&(student.getStuld()==stuld);
}
return false;
}
相关代码:
package com.imooc.student;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
public class StudentTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//定义三个Student类的对象及一个HashSet类的对象
Student one=new Student(3,"William",65.0f);
Student two=new Student(1,"Tom",87.0f);
Student three=new Student(2,"Lucy",95.0f);
Set set=new HashSet();
//将Student类的对象添加到集合中
set.add(one);
set.add(two);
set.add(three);
//使用迭代器显示Student类的对象中的内容
Iterator it=set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
//添加重复数据和one一样的数据
Student one01=new Student(3,"William",65.0f);
set.add(one01);
System.out.println("*******************************");
System.out.println("添加重复数据后的学生学生信息");
it=set.iterator();
while(it.hasNext()) {
System.out.println(it.next());
}
}
}
27
收起
正在回答
1回答
同学你好,已完成练习,代码实现符合题目要求,很棒,继续加油哦!
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星