You can structure your equals method similarly to an if statement. You just need to cast the other argument first before your can compare their fields.
@Override
public boolean equals(Object o) {
// Check if the other object is also a Student
if (o instanceof Student) {
// Now that we know o is a student, we can safely cast it
Student other = (Student) o;
// Similarly to how you would write an if statement you can compare each individual field.
// Thanks to inheritance, we defer the equality check of each field to its own implementation
return this.firstName.equals(other.firstName)
&& this.lastName.equals(other.lastName)
&& this.birthDate.equals(other.birthDate);
}
// Other object was not a student
return false;
}
You then need to go write something similar in Date so that when you compare birthDate, it will know what to do.
You can also take this one step farther by using Objects.equals(a, b) instead of a.equals(b). This will ensure you do not get a nullPointerException if a happens to be null when comparing them. However, since this looks to be a school project I imagine you may be expected to either check manually or assume the values will not be null instead of using the standard library.
You can structure your equals method similarly to an if statement. You just need to cast the other argument first before your can compare their fields.
@Override
public boolean equals(Object o) {
// Check if the other object is also a Student
if (o instanceof Student) {
// Now that we know o is a student, we can safely cast it
Student other = (Student) o;
// Similarly to how you would write an if statement you can compare each individual field.
// Thanks to inheritance, we defer the equality check of each field to its own implementation
return this.firstName.equals(other.firstName)
&& this.lastName.equals(other.lastName)
&& this.birthDate.equals(other.birthDate);
}
// Other object was not a student
return false;
}
You then need to go write something similar in Date so that when you compare birthDate, it will know what to do.
You can also take this one step farther by using Objects.equals(a, b) instead of a.equals(b). This will ensure you do not get a nullPointerException if a happens to be null when comparing them. However, since this looks to be a school project I imagine you may be expected to either check manually or assume the values will not be null instead of using the standard library.
For equals to work, you need to override hashCode also. Further equality check needs actual comparison of your objects.
Also, any related objects also has to implement hashCode and equals method. In this case Date.
Possible code
import java.util.Objects;
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;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Date date = (Date) o;
return day == date.day &&
month == date.month &&
year == date.year;
}
@Override
public int hashCode() {
return Objects.hash(day, month, year);
}
}
public class Student {
private final String firstName;
private final String lastName;
private Date birthDate;
public Student(String firstName, String lastName, Date birthDate) {
this.firstName = firstName;
this.lastName = lastName;
this.birthDate = birthDate;
}
public static void main(String[] args) {
System.out.println(new Student("John", "Johnny", new Date(10, 10, 10))
.equals(new Student("John", "Johnny", new Date(10, 10, 10))));
System.out.println(new Student("John", "Johnny", new Date(11, 10, 10))
.equals(new Student("John", "Johnny", new Date(10, 10, 10))));
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Student student = (Student) o;
return Objects.equals(firstName, student.firstName) &&
Objects.equals(lastName, student.lastName) &&
Objects.equals(birthDate, student.birthDate);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, birthDate);
}
}
How does Java "==" operator check equality between objects? Trying to understand how Object.equals() works
Comparing Java objects with different member variables - Software Engineering Stack Exchange
How to compare two java objects - Stack Overflow
How to compare two Java objects?
Videos
I'm wondering how "==" is implemented to check equality between two objects. The internet say's the Object superclass, .equals() is defined as:
public boolean equals(Object obj) {
return (this == obj);
}How does a simple "==" check equality between two objects? Hashcode, a bitwise AND of the sum of all data? I can't find anywhere that explains in depth how two objects are compared.
The “different member variables” is irrelevant. It’s an implementation detail. What you need is a set of rules which of two people comes first.
You could for example sort by family name, then given name, then date of birth, and if these are all three equal, take the name of the school, university or company (which will be different member variables) and compare them as strings. If that is equal, you might have student and employee ids, and the student ids might be unique, and the employee ids might be unique, but student and employee ids might be the same. So you could sort then students first ordered by id, followed by employees sorted by id, if you might sort by if first if student and employee ids are comparable.
(University or school and employer might be the same, because universities are also employers).
Comparing objects with different fields sounds like bad polymorphic design, whether it's Java or any other OOP language:
- If your comparator needs to know the precise subtype of an object to do the comparison, you mess-up with the the open-closed principle, since for every new subclassing, you'd potentially need to modify the comparator to select the relevant fields.
- If your comparator needs uses reflexion to find on its own the relevant fields to compare, you indirectly mess up with the principle of encapsulation, since you create a hidden requirement that information to be compared must be in some predetermined field.
If you want to sort People properly in a clean polymorphic design:
- you need to rely either on a field, available for any kind of
People, includingStudent, or - you may call some function/transformation that provides a unique value (e.g. a string) that allows to sort any
People.PeopleandStudentmay then just use a different transformation that will be passed to the comparator; Or - you only sort among homogeneous subtypes.
You need to provide your own implementation of equals() in MyClass.
@Override
public boolean equals(Object other) {
if (!(other instanceof MyClass)) {
return false;
}
MyClass that = (MyClass) other;
// Custom equality check here.
return this.field1.equals(that.field1)
&& this.field2.equals(that.field2);
}
You should also override hashCode() if there's any chance of your objects being used in a hash table. A reasonable implementation would be to combine the hash codes of the object's fields with something like:
@Override
public int hashCode() {
int hashCode = 1;
hashCode = hashCode * 37 + this.field1.hashCode();
hashCode = hashCode * 37 + this.field2.hashCode();
return hashCode;
}
See this question for more details on implementing a hash function.
You need to Override equals and hashCode.
equals will compare the objects for equality according to the properties you need and hashCode is mandatory in order for your objects to be used correctly in Collections and Maps
Hi there, it's my first time learning Java and I'd love some assistance with comparing two Java objects. Here is a KenoBall class:
public class KenoBall {
private static int number;
private static String colour;
private static String ball;
public KenoBall(int number, String colour) {
this.number = number;
this.colour = colour;
this.ball = number + colour;
System.out.print(number + colour + "\n");
}
public boolean matches(KenoBall other) {
if (What goes in here?) {
System.out.println("Tru");
return true;
} else {
System.out.println("False");
return false;
}
}
}And in my main method:
public static void main(String[] args) {
KenoBall k1 = new KenoBall(1, "R");
KenoBall k2 = new KenoBall(1, "R");
KenoBall k3 = new KenoBall(4, "B");
k1.matches(k2);
}If anyone can point me in the right direction I'd really appreciate it! Basically I'm trying to see if k1 is equal to k2 (and it should).
Thank you!