I want to know how to check if two objects of the same class have the same values in each attribute.
For example:
public class Person {
String name;
String surname;
String country;
int age;
public Person(String name, String surname, String country, int age) {
this.name = name;
this.surname = surname;
this.country = country;
this.age = age;
}
public boolean samePerson(Person person){
//CODE
}
Person person1 = new Person("Abel", "Smith", "EEUU", 26);
Person person2 = new Person("Alexa", "Williams", "Canada", 30);
Person person3 = new Person("Abel", "Smith", "EEUU", 26);
Person person4 = new Person("Alexa", "Williams", "EEUU", 30)
person1.samePerson(person2) // return false
person1.samePerson(person3) // return true
person2.samePerson(person3) // return false
person2.samePerson(person4) // return false
The only thing I can think of is to compare the attributes one to one. Is there a simpler way?
Sorry for my english
Thanks in advance
The only thing I can think of is to compare the attributes one to one. Is there a simpler way?
Unfortunately not. You'll have to write code to do just that. And if you do, consider putting that code in equals
and hashCode
methods.
There is no simpler way. You have to implement your own way of doing this because it is a class you made yourself.
You are off to a good start. You can use your samePerson()
method to provide this
functionality, or, like @Thilo said, use the equals
and hashCode
methods.
It should go along the lines of:
public boolean samePerson(Person person){
return this.name.equals(person.name) &&
this.surname.equals(person.surname) &&
this.country.equals(person.country) &&
this.age == person.age;
}
With perhaps some sanity null checking and whatever else you require.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With