How to Override the equals() Method in Java
Overriding the equals() method is essential for customizing the equality comparison behavior for custom objects in Java. Here's a comprehensive guide to help you do that effectively:
The Problem:
In the snippet given, you encountered an error when attempting to compare age fields using equals(), as it's designed for String objects. Integer values require the usage of == operator.
The Solution:
To resolve this error, use the == operator to compare primitive data types such as age. The modified code snippet is as follows:
public boolean equals(People other){ boolean result; if((other == null) || (getClass() != other.getClass())){ result = false; } // end if else{ People otherPeople = (People)other; result = name.equals(other.name) && age == other.age; } // end else return result; } // end equals
Additional Explanation:
1. Overriding Process:
- To override equals(), declare it with the @Override annotation.
- The method should return a boolean indicating equality, taking one argument of the same type as the class.
2. Null Check:
- Always check for null using obj == null to avoid NullPointerExceptions.
3. Class Comparison:
- Verify that the object to be compared is of the same class using getClass() != other.getClass().
4. Custom Comparison Logic:
- Define the custom comparison logic within the else block.
- Use equals() for String comparisons and == for primitive types.
- Consider all relevant fields that determine equality.
Example:
The provided example overrides equals() for the Person class, comparing both name and age for equality:
public boolean equals(Object obj) { if (obj == null) { return false; } if (obj.getClass() != this.getClass()) { return false; } final Person other = (Person) obj; if ((this.name == null) ? (other.name != null) : !this.name.equals(other.name)) { return false; } if (this.age != other.age) { return false; } return true; }
Conclusion:
Overriding the equals() method empowers you to define customized equality comparisons for your custom objects. By carefully following the steps and examples provided, you can effectively compare objects based on their specific attributes.
The above is the detailed content of How to Properly Override the equals() Method in Java?. For more information, please follow other related articles on the PHP Chinese website!

This article analyzes the top four JavaScript frameworks (React, Angular, Vue, Svelte) in 2025, comparing their performance, scalability, and future prospects. While all remain dominant due to strong communities and ecosystems, their relative popul

This article addresses the CVE-2022-1471 vulnerability in SnakeYAML, a critical flaw allowing remote code execution. It details how upgrading Spring Boot applications to SnakeYAML 1.33 or later mitigates this risk, emphasizing that dependency updat

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

Node.js 20 significantly enhances performance via V8 engine improvements, notably faster garbage collection and I/O. New features include better WebAssembly support and refined debugging tools, boosting developer productivity and application speed.

This article explores integrating functional programming into Java using lambda expressions, Streams API, method references, and Optional. It highlights benefits like improved code readability and maintainability through conciseness and immutability

Iceberg, an open table format for large analytical datasets, improves data lake performance and scalability. It addresses limitations of Parquet/ORC through internal metadata management, enabling efficient schema evolution, time travel, concurrent w

This article explores methods for sharing data between Cucumber steps, comparing scenario context, global variables, argument passing, and data structures. It emphasizes best practices for maintainability, including concise context use, descriptive


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Dreamweaver CS6
Visual web development tools

Atom editor mac version download
The most popular open source editor

SublimeText3 English version
Recommended: Win version, supports code prompts!
