
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to compare two arrays in Java?
Arrays can be compared using following ways in Java
Using Arrays.equals(array1, array2) methods − This method iterates over each value of an array and compare using equals method.
Using Arrays.deepEquals(array1, array2) methods − This method iterates over each value of an array and deep compare using any overridden equals method.
Using == on array will not give the desired result and it will compare them as objects. See the example below for each of the comparison way.
Example
import java.util.Arrays; public class Tester{ public static void main(String[] args) { int[] array1 = {1, 2, 3}; int[] array2 = {1, 2, 3}; System.out.println("Arrays: array1 = [1, 2, 3], array 2 = [1, 2, 3]"); //Scenario 1 : Comparing using == System.out.println("== results: " + (array1 == array2)); //Scenario 2 : Comparing using Arrays.equals() System.out.println("Arrays.equals() results: " + Arrays.equals(array1,array2)); Object[] objArray1 = {array1}; Object[] objArray2 = {array2}; System.out.println("Arrays: objArray1 = {array1}, objArray1 = {array2}"); //Scenario 3 : Comparing using Arrays.equals() System.out.println("Arrays.equals() results: " + Arrays.equals(objArray1,objArray2)); //Scenario 4 : Comparing using Arrays.deepEquals() System.out.println("Arrays.deepEquals() results: " + Arrays.deepEquals(objArray1,objArray2)); } }
Output
Arrays: array1 = [1, 2, 3], array 2 = [1, 2, 3] == results: false Arrays.equals() results: true Arrays: objArray1 = {array1}, objArray1 = {array2} Arrays.equals() results: false Arrays.deepEquals() results: true
Advertisements