【发布时间】:2013-08-21 11:01:35
【问题描述】:
所以我不确定为什么下面的代码会返回“它们不相等”。从检查它应该返回“他们是平等的”。谁能帮我吗?提前谢谢你。
public class BenAndLiam {
public static void main(String[] args){
String[] name = new String[2];
name[0] = "Liam";
name[1] = "Short";
int[] marks = new int[3];
marks[0] = 90;
marks[1] = 50;
marks[2] = 70;
//make students
Student Liam = new Student(1111, name, marks);
Student Ben = new Student(1111, name, marks);
//print Liam's info
System.out.println(Liam.getId() + " " + Liam.getName()[0] + " " +
Liam.getName()[1] + " " + Liam.getMarks()[0] + " " + Liam.getMarks()[1] +
" " + Liam.getMarks()[2]);
System.out.println(Ben.getId() + " " + Ben.getName()[0] + " " +
Ben.getName()[1] + " " + Ben.getMarks()[0] + " " + Ben.getMarks()[1] +
" " + Ben.getMarks()[2]);
//check for equality
if(Ben.equals(Liam))
System.out.println("They're equal");
else System.out.println("They're not equal");
}
}
我的学生代码:
public class Student {
//The aspects of a student
private int id;
private String name[];
private int marks[];
//Constructor 1
public Student(int id, String name[]){
this.id = id;
this.name = name;
}
//Constructor 2
public Student(int id, String name[], int marks[]){
setId(id);
setName(name);
setMarks(marks);
}
//accessor for id
public int getId(){
return id;
}
//accessor for name
public String getName()[]{
return name;
}
//accessor for marks
public int getMarks()[]{
return marks;
}
//Mutator for id
public void setId(int id){
this.id = id;
}
//mutator for name
public void setName(String name[]){
this.name = name;
}
//Mutator for marks
public void setMarks(int marks[]){
this.marks = marks;
}
}
从表面上看,我需要为在我的 Student 类中使用 equals() 设置某种标题?
更新: 我刚刚通过将此代码添加到我的学生类中使其工作:
public boolean equals(Student otherstudent){
return ((id == otherstudent.id) && (name.equals(otherstudent.name)
&& (marks == otherstudent.marks)));
}
干杯!
【问题讨论】:
-
你能展示一下student的equals方法吗?你应该重写这个方法并在那里处理你的逻辑。
-
发布
Student的代码。你定义了equals吗? -
您是否记得在您的
Student类中覆盖equals()和hashCode()? -
我刚刚为学生添加了代码。请参阅我的原始帖子。
-
我成功了!我没有在学生课上描述(这是正确的术语)我的方法。这是我在学生课中输入的代码: public boolean equals(Student otherstudent){ return ((id == othersstudent.id) && (name.equals(otherstudent.name) && (marks == othersstudent.marks))) ;干杯伙计们!
标签: java