I tried to perform a comparison between two objects of the same class. Actually, I wanted to compare the content of the both the objects. Here, the objects are of class Student. In class Student I have defined a static method called equals()
as shown below.
By doing so, will my intention be accomplished (compare the names and birthdays of both students)? If not what is happening here?
The problem is that I don't get the answer I expect. The output is false
even though it must be true
.
public class Main {
public static void main(String[] args) {
Student a = new Student("John", "Johnny");
Student b = new Student("John", "Johnny");
a.setBirthDate(10, 10, 10);
b.setBirthDate(10, 10, 10);
boolean ans = Student.equals(a, b);
System.out.println(ans);
}
}
public class Date {
public int day;
public int month;
public int year;
public Date(int d, int m, int y) {
this.day = d;
this.month = m;
this.year = y;
}
}
public class Student{
private String firstName;
private String lastName;
private Date birthDate;
public Student(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public void setBirthDate(int day, int month, int year) {
Date b_day = new Date(day, month, year);
birthDate = b_day;
}
public static boolean equals(Student a, Student b) {
if (a.equals(b)) { //is this comparison wrong?
return true;
}
return false;
}
}
Later, I modified the equals()
method as follows too. But still the output is false
though it must be true
.
public static boolean equals(Student a, Student b) {
//we cannot use == operator because this operator compares the references (memory locations) of a and b rather than their content. Therefore, the best option is to use equals(Object obj) method.
//however, in the case of String comparison below, since the 'new' operator is not used, there's no problem in using either(because of string pool)
if (a.firstName.equals(b.firstName) && a.lastName.equals(b.lastName) && a.birthDate.equals(b.birthDate)) {
return true;
}
return false;
}
Please can you tell me what's wrong with my implementation of the equals()
method in both the scenarios depicted above.
Thanks in advance.
Edited:
I have overridden the equals method now as follows. But still I face the same issue. I suspect that there's something wrong with the Date
class. But the problem is that I'm not quite sure of it. Also, I don't understand how to remedy the problem. Can someone please tell me what's wrong here.
@Override
public boolean equals(Object student) {
System.out.println(this.firstName);
System.out.println(this.lastName);
System.out.println(this.birthDate);
System.out.println(((Student)student).firstName);
System.out.println(((Student)student).lastName);
System.out.println(((Student)student).birthDate);
return super.equals(student);
}