Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Check if two objects of the same class have identical values

Tags:

java

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

like image 724
Peskalberto Avatar asked Sep 19 '25 00:09

Peskalberto


2 Answers

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.

like image 94
Thilo Avatar answered Sep 20 '25 16:09

Thilo


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.

like image 20
Illidanek Avatar answered Sep 20 '25 16:09

Illidanek