Table of Contents
introduce
method
There are two standard methods
Example 1: Overriding the equals() method
Explanation
Output
Example 2: Not overriding the equals() method
Example 3: Using hashCode() and equals() methods
解释
输出
结论
Home Java javaTutorial Java program to compare two objects

Java program to compare two objects

Aug 31, 2023 pm 03:45 PM
java comparison object isequals

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;
   }
}
Copy after login
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
Copy after login
Copy after login

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;
   }
}
Copy after login
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
Copy after login
Copy after login

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;
   }
}
Copy after login

Explanation

的中文翻译为:

解释

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

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

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

输出

The two person objects are equal
Copy after login

结论

  • 这个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 of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles