Home > Java > javaTutorial > Java Array Comparison: `equals()` vs. `Arrays.equals()` - What's the Difference?

Java Array Comparison: `equals()` vs. `Arrays.equals()` - What's the Difference?

Patricia Arquette
Release: 2024-12-28 16:51:12
Original
255 people have browsed it

Java Array Comparison:  `equals()` vs. `Arrays.equals()` - What's the Difference?

Comparing Arrays in Java: equals vs Arrays.equals

When comparing array objects in Java, it's important to understand the subtle differences between equals and Arrays.equals.

equals Operator

The equals operator in Java compares whether two references refer to the same object in memory. When applied to arrays, this means it checks if the two array references are pointing to the same array instance.

Object[] array1, array2;
array1.equals(array2);
Copy after login

In this case, if array1 and array2 refer to the same array object, the result will be true. Otherwise, it will be false.

Arrays.equals Method

In contrast, the Arrays.equals method compares the contents of two arrays. It checks if the arrays have the same number of elements and if the corresponding elements are equal.

Arrays.equals(array1, array2);
Copy after login

If array1 and array2 have the same contents, the result will be true. Otherwise, it will be false.

Key Differences

The key difference between equals and Arrays.equals is that equals compares references while Arrays.equals compares contents.

Examples

Consider the following examples:

Object[] array1 = new int[] { 1, 2, 3 };
Object[] array2 = new int[] { 1, 2, 3 };
Copy after login

In this case, array1.equals(array2) will be false because array1 and array2 are two different array objects. However, Arrays.equals(array1, array2) will be true because the contents of the arrays are the same.

Object[] array1 = new int[] { 1, 2, 3 };
Object[] array2 = array1;
Copy after login

In this case, array1.equals(array2) and Arrays.equals(array1, array2) will both be true because array1 and array2 refer to the same array object.

The above is the detailed content of Java Array Comparison: `equals()` vs. `Arrays.equals()` - What's the Difference?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template