没有什么规则,你们自己定义就好,看需求。例如一共有10个字段,你们认可hashcode只考虑其中七个重要字段就好,那就用7个字段。
2019-09-11 17:56:05
public class Student{
//根据需求完成Student类的定义
private int stuld;
private String name;
private float score;
public Student(int id,String name,float score){
setStuid(id);
setName(name);
setScore(score);
}
public void setStuid(int id){
this.stuld = id;
}
public int getStuid(){
return stuld;
}
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
public void setScore(float score)
{
this.score = score;
}
public float getScore()
{
return score;
}
public String toString()
{
return "[学号:"+getStuid()+",姓名:"+getName()+"成绩:"+getScore()+"]";
}
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + stuld;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(score);
return result;
}
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()==stuld);
}
return false;
}
}
2019-09-11 17:58:19
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + stuld;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + Float.floatToIntBits(score);
return result;
}
像这个hashcode 我使用eclipse自动生成的,如果自己写怎么写?float参数为什么用floatToIntBits(score);??
2019-09-11 17:59:50
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星