Home  >  Article  >  Java  >  Java program to compare two objects

Java program to compare two objects

王林
王林forward
2023-08-31 15:45:121105browse

Java program to compare two objects

introduce

In Java, you can use the equals() method to compare objects. This method determines whether two objects are equal based on the properties of the object. When comparing objects in Java, it is very important to override the equals() method in the class to ensure that the comparison is based on the required properties.

This Java program compares two objects of type Person by overriding the equals() method and compares them based on their name and age attributes. First use the equals() method to check whether the objects belong to the same class, and then compare the name and age attributes. If both properties match, the method returns true, indicating that the objects are equal. If any of the properties are different, the method returns false, indicating that the objects are not equal.

method

There are two standard methods

  • Use equals() method

    • Not covered

    • Use override

  • Use hashCode() and equals() methods

Example 1: Overriding the equals() method

Overriding the equals() method in a class allows custom comparisons based on the properties of the object.

method

  • We first define a Person class, which contains two private instance variables: name and age.

  • We define a constructor for the Person class that accepts a name and age and initializes the instance variables with these values.

  • We overridden the equals() method in the Person class to compare two Person objects based on name and age. The equals() method accepts an Object parameter. We first check whether the parameter is not empty and is an instance of the Person class. We then convert that object to a Person object and compare its name and age properties to the current object's name and age properties.

  • In the main() method, we create two Person objects with different names and age values.

  • We call the equals() method on the first Person object and pass in the second Person object as a parameter. The equals() method returns a Boolean value indicating whether the two objects are equal.

  • Finally, we use System.out.println() to print the comparison results to the console

public class ObjectComparator {
    
   public static void main(String[] args) {
        
      // Create two objects to compare
      Person person1 = new Person("Alice", 25);
      Person person2 = new Person("Bob", 30);
        
      // Compare the two objects
      boolean areEqual = person1.equals(person2);
      System.out.println("Are the two objects equal? " + areEqual);
   }
}

class Person {
    
   private String name;
   private int age;
    
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
    
   @Override
   public boolean equals(Object obj) {
      if (obj == null) return false;
      if (!(obj instanceof Person)) return false;
      Person otherPerson = (Person) obj;
      return this.name.equals(otherPerson.name) && this.age == otherPerson.age;
   }
}
The Chinese translation of

Explanation

is:

Explanation

In this example, we create two Person objects with different names and ages, and then call the equals method of the first object to compare it with the second object. equals method is defined in Person class and checks if both objects have the same name and age properties. Finally, we print the results of the comparison to the console.

Output

Are the two objects equal? false

Example 2: Not overriding the equals() method

The equals() method is not overridden, and objects are compared based on their references rather than properties.

method

  • We first define a Person class, which contains two private instance variables: name and age.

  • We define a constructor for the Person class that accepts a name and age and initializes the instance variables with these values.

  • In the main() method, we create two Person objects with the same name and age values.

  • We call the equals() method on the first Person object and pass in the second Person object as a parameter. Since we did not override the equals() method in the Person class, the default implementation of the equals() method inherited from the Object class is used. The implementation checks whether the two objects are the same object (i.e. have the same memory address) and returns true if they are. Since the person1 and person2 objects have different memory addresses, the equals() method returns false.

  • Finally, we use System.out.println() to print the comparison results to the console.

public class ObjectComparator {
    
   public static void main(String[] args) {
        
      // Create two objects to compare
      Person person1 = new Person("Alice", 25);
      Person person2 = new Person("Alice", 25);
        
      // Compare the two objects
      boolean areEqual = person1.equals(person2);
      System.out.println("Are the two objects equal? " + areEqual);
   }
}

class Person {
    
   private String name;
   private int age;
    
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
}
The Chinese translation of

Explanation

is:

Explanation

In this example, we create two Person objects with the same name and age, and then call the equals method to compare the first object with the second object. Since we did not override the equals method in the Person class, the default implementation inherited from the Object class is used. This implementation checks whether the two objects are the same object (i.e. have the same memory address) and returns true if so. Since the person1 and person2 objects have different memory addresses, the equals method returns false. Finally, we print the results of the comparison to the console.

Output

Are the two objects equal? false

Example 3: Using hashCode() and equals() methods

The equals() method is not overridden, and objects are compared based on their references rather than properties.

method

  • We created two objects of the Person class, person1 and person2, whose names and ages are the same.

  • We then call the hashCode() and equals() methods on person1.

  • In the Person class, we override the hashCode() method and use the Objects.hash() method to generate a hash code based on the name and age attributes of the object.

  • 然后我们重写equals()方法,根据它们的姓名和年龄属性来比较两个Person对象。该方法首先检查对象是否属于同一类,如果是,则使用Objects.equals()方法检查它们的姓名和年龄属性是否相等。

  • 在main()方法中,我们使用&&运算符通过hashCode()方法检查person1和person2的哈希码是否相同,并且通过equals()方法返回true。

  • 最后,我们打印出一个消息,指示这些对象是否相等。

public class ObjectComparator {
    
   public static void main(String[] args) {
        
      // Create two objects to compare
      Person person1 = new Person("Alice", 25);
      Person person2 = new Person("Alice", 25);
        
      // Compare the two objects using hashCode and equals methods
      boolean areEqual = person1.hashCode() == person2.hashCode() && person1.equals(person2);
      System.out.println("Are the two objects equal? " + areEqual);
   }
}

class Person {
    
   private String name;
   private int age;
    
   public Person(String name, int age) {
      this.name = name;
      this.age = age;
   }
    
   @Override
   public int hashCode() {
      return Objects.hash(name, age);
   }
    
   @Override
   public boolean equals(Object obj) {
      if (this == obj)
         return true;
      if (!(obj instanceof Person))
         return false;
      Person other = (Person) obj;
      return Objects.equals(name, other.name) && age == other.age;
   }
}

Explanation

的中文翻译为:

解释

在这个例子中,我们创建了两个具有相同姓名和年龄的Person对象,然后调用第一个对象的hashCode()和equals()方法来与第二个对象进行比较。

在Person类中,我们重写了hashCode()和equals()方法,以便根据它们的name和age属性来比较对象。hashCode()方法返回name和age属性的组合的哈希码,equals()方法检查对象是否属于同一类,并且具有相同的name和age属性。

最后,我们使用&&运算符来检查两个对象的哈希码是否相同,并且equals()方法是否返回true。如果两个条件都为true,我们打印出对象相等的信息。否则,我们打印出对象不相等的信息。

输出

The two person objects are equal

结论

  • 这个Java程序使用equals()方法来比较两个Person对象的属性,该方法已在Person类中被重写。

  • 该程序展示了定制对象比较的重要性,并突出了Java在实现自定义比较逻辑方面提供的灵活性。

The above is the detailed content of Java program to compare two objects. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete