The Wayback Machine - https://web.archive.org/web/20240915113925/https://www.geeksforgeeks.org/compare-two-arrays-java/
Open In App

Compare Two Arrays in Java

Last Updated : 31 May, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

While comparing two arrays we can not use “==” operator as it will compare the addresses of the memory block to which both the arrays are pointing. If we want to compare the elements inside the array we need to figure out other ways instead of using arithmetic operators. As we all know arrays data structures possess the property of containing elements in a continuous manner because of which we can calculate the size of both the arrays using the size() method of Arrays class itself, and can start comparing the indices if the size of both arrays is found to be equal.

Illustration:

Java




// Java Program to Illustrate
// Comparison of Arrays
// Using == Operators
 
// Importing required classes
import java.util.*;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declaring integer arrays and
        // initializing them with custom values
        int arr1[] = { 1, 2, 3 };
        int arr2[] = { 1, 2, 3 };
 
        // Comparing arrays if equal or not
        // using == operator
        if (arr1 == arr2)
 
            // Print statement
            System.out.println("Same");
        else
 
            // Print statement
            System.out.println("Not same");
    }
}


Output

Not same

Output explanation: In Java, arrays are first class objects. In the above program, arr1 and arr2 are two references to two different objects. So when we compare arr1 and arr2, two reference variables are compared, therefore we get the output as “Not Same”.

How to Compare Array Contents? 

A simple way is to run a loop and compare elements one by one. Java provides a direct method Arrays.equals() to compare two arrays. Actually, there is a list of equals() methods in the Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is the base of all classes in Java). 

Example:

Java




// Java Program to Check If Two Arrays Are Equal
// Using equals() method of Arrays class
 
// Importing required classes
import java.util.Arrays;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declaring integer arrays
        int arr1[] = { 1, 2, 3 };
        int arr2[] = { 1, 2, 3 };
 
        // Checking if above two arrays are equal
        // using equals() method
        if (Arrays.equals(arr1, arr2))
 
            // Print statement if arrays are equal
            System.out.println("Same");
        else
 
            // Print statement if arrays are equal
            System.out.println("Not same");
    }
}


Output

Same

Output explanation: As seen above, the Arrays.equals() works fine and compares arrays contents. Now the question, what if the arrays contain arrays inside them or some other references which refer to different objects but have the same values. For example, refer to the below program as follows.

How to Deep Compare Array Contents?   

Example 1-A:

Java




// Java Program to Check If Two Arrays Are Equal
// Using equals() method of Arrays class
 
// Importing required classes
import java.util.Arrays;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
        // Declaring and initializing integer arrays
        // having same values
 
        // Array 1
        int inarr1[] = { 1, 2, 3 };
        // // Array 2
        int inarr2[] = { 1, 2, 3 };
 
        // // Array 1 contains only one element
        Object[] arr1 = { inarr1 };
        // Array 2 also contains only one element
        Object[] arr2 = { inarr2 };
 
        // Checking if arrays are equal or not
        // using equals() method
        if (Arrays.equals(arr1, arr2))
 
            // Print statement if arrays are same
            System.out.println("Same");
        else
 
            // Print statement if arrays are not same
            System.out.println("Not same");
    }
}


Output

Not same

Output explanation: So Arrays.equals() is not able to do a deep comparison. Java provides another method for this Arrays.deepEquals() which does the deep comparison.

Example 1-B:

Java




// Java Program to Check If Two Arrays Are Equal
// Using deepEquals() method of Arrays class
 
// Importing required classes
import java.util.Arrays;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declaring and initializing integer arrays
        // having same values
 
        // Array 1
        int inarr1[] = { 1, 2, 3 };
        // Array 2
        int inarr2[] = { 1, 2, 3 };
 
        // Array 1 contains only one element
        Object[] arr1 = { inarr1 };
        // Array 2 also contains only one element
        Object[] arr2 = { inarr2 };
 
        // Checking if arrays are equal or not
        // using deepEquals() method
        if (Arrays.deepEquals(arr1, arr2))
 
            // Print statement if arrays are same
            System.out.println("Same");
        else
 
            // Print statement if arrays are not same
            System.out.println("Not same");
    }
}


Output

Same

Output Explanation: Let us now understand how does deepEquals() method of the Arrays class work internally. It compares two objects using any custom equals() methods they may have (if they have an equals() method implemented other than Object.equals()). If not, this method will then proceed to compare the objects field by field, recursively. As each field is encountered, it will attempt to use the derived equals() if it exists, otherwise, it will continue to recurse further. 

This method works on a cyclic Object graph like this: A->B->C->A. It has cycle detection so ANY two objects can be compared, and it will never enter into an endless loop.

Example 1-C:  

Java




// Java Program to Check If Two Arrays Are Equal
// Using deepEquals() method of Arrays class
 
// Importing required classes
import java.util.Arrays;
 
// Main class
class GFG {
 
    // Main driver method
    public static void main(String[] args)
    {
 
        // Declaring and initializing integer arrays
        // having same values
 
        // Array 1
        int inarr1[] = { 1, 2, 3 };
        // Array 2
        int inarr2[] = { 1, 2, 3 };
 
        // Array 1 contains only one element
        Object[] arr1 = { inarr1 };
        // Array 2 also contains only one element
        Object[] arr2 = { inarr2 };
 
        // outarr1 contains only one element
        Object[] outarr1 = { arr1 };
        // outarr2 also contains only one element
        Object[] outarr2 = { arr2 };
 
        // Checking if arrays are equal or not
        // using deepEquals() method
        if (Arrays.deepEquals(outarr1, outarr2))
 
            // Print statement if arrays are same
            System.out.println("Same");
        else
 
            // Print statement if arrays are not same
            System.out.println("Not same");
    }
}


Output

Same


Similar Reads

Java Arrays compare() Method with Examples
Arrays compare() method in Java comes under the Arrays class and java.util package. This method compares two arrays lexicographically (Dictionary order). There are two different versions of different overloads for Boolean, byte, char, double, float, int, long, short, and Object arrays. This method returns values as per the below-mentioned cases. It
4 min read
Compare two Strings in Java
The string is a sequence of characters. In Java, objects of String are immutable which means they are constant and cannot be changed once created. Methods to Compare Strings in JavaBelow are 5 ways to compare two Strings in Java: Using user-defined functionUsing String.equals()Using String.equalsIgnoreCase()Using Objects.equals()Using String.compar
7 min read
Compare two strings lexicographically in Java
In this article, we will discuss how we can compare two strings lexicographically in Java. One solution is to use Java compareTo() method. The method compareTo() is used for comparing two strings lexicographically in Java. Each character of both the strings is converted into a Unicode value for comparison. int compareTo(String str) :It returns the
3 min read
Java.util.Arrays.parallelSetAll(), Arrays.setAll() in Java
Prerequisites : Lambda Expression in Java 8IntUnaryOperator Interface parallelSetAll and setAll are introduced in Arrays class in java 8. parallelSetAll(): It set all the element in the specified array in parallel by the function which compute each element. Syntax: public static void parallelSetAll(double[] arr, IntToDoubleFunction g) Parameters :
5 min read
Java Integer compare() method
The compare() method of Integer class of java.lang package compares two integer values (x, y) given as a parameter and returns the value zero if (x==y), if (x < y) then it returns a value less than zero and if (x > y) then it returns a value greater than zero. Syntax : public static int compare(int x, int y) Parameter : x : the first int to c
2 min read
Short compare() method in Java
The compare() method of Short class is used to compare two primitive short values for numerical equality. As it is a static method therefore it can be used without creating any object of Short. Syntax: public static int compare(short x, short y) Parameters: This method accepts two parameters: x: which is the first Short object to be compared. y: wh
2 min read
Boolean compare() method in Java with Examples
The compare() method of Boolean class is a built in method in Java which is used to compare two boolean values. It is a static method, so it can be called without creating any object of the Boolean class i.e. directly using the class name. Syntax: Boolean.compare(boolean a, boolean b) Parameters: It takes two boolean values a and b in the parameter
2 min read
Byte compare() method in Java with examples
The compare() method of Byte class is a built in method in Java which is used to compare two byte values. Syntax Byte.compare(byte a, byte b) Parameters: It takes two byte value 'a' and 'b' as input in the parameters which are to be compared. Return Value: It returns an int value. It returns: 0 if 'a is equal to 'b, a positive value 'a' is greater
2 min read
Compare Dates in Java
The Date class represents a specific instant in time, with millisecond precision. The Date class of java.util package implements Serializable, Cloneable and Comparable interface. It provides constructors and methods to deal with date and time with java. The following are the methods to compare dates in java Method - 1: Using Date.compareTo():Steps
3 min read
Float compare() Method in Java with Examples
The compare() method of Float Class is a built-in method in Java that compares the two specified float values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call. Syntax: public static int compare(float f1, float f2)Parameters: The function accepts two parameters: f1: The first floa
2 min read
Java | ==, equals(), compareTo(), equalsIgnoreCase() and compare()
There are many ways to compare two Strings in Java: Using == operatorUsing equals() methodUsing compareTo() methodUsing compareToIgnoreCase() methodUsing compare() method Method 1: using == operator Double equals operator is used to compare two or more than two objects, If they are referring to the same object then return true, otherwise return fal
7 min read
Java Guava | Booleans.compare() method with Examples
The compare() method of Booleans Class in the Guava library is used to compare the two specified boolean values. These values are passed as the parameter and the result of comparison is found as the difference of 1st value and the 2nd value. Hence it can be positive, zero or negative. Syntax: public static int compare(boolean a, boolean b) Paramete
2 min read
Java Guava | Ints.compare() method with Examples
Ints.compare() is a method of Ints class in Guava library which is used to compare the two given int values. It takes two integers as parameters that are to be compared. It returns a comparator value based on the comparison of the specified integers.Syntax : public static int compare(int a, int b) Parameters: This method takes two parameters: a: wh
2 min read
Java Guava | compare() method of Short Class with Examples
Shorts.compare() method of Guava's Shorts Class is used to compare the two specified short values. These values are passed as the parameter and the result of comparison is found as the difference of 1st value and the 2nd value. Hence it can be positive, zero or negative. Syntax: public static int compare(short x, short y) Parameters: This method ac
2 min read
Java Guava | Floats.compare() method with Examples
Floats.compare() method of Floats Class is used to compare the two specified float values. These values are passed as the parameter and the result of comparison is found as the difference of 1st value and the 2nd value. Hence it can be positive, zero or negative. Syntax: public static int compare(float a, float b) Parameters: This method accepts tw
2 min read
Java Guava | Longs.compare() method with Examples
Longs.compare() method of Guava's Longs Class is used to compare the two specified long values. These values are passed as the parameter and the result of comparison is found as the difference of 1st value and the 2nd value. Hence it can be positive, zero or negative. Syntax: public static int compare(long a, long b) Parameters: This method accepts
2 min read
Java Guava | Chars.compare() method with Examples
Chars.compare() method of Guava's Chars Class is used to compare the two specified char values. These values are passed as the parameter and the result of comparison is found as the difference of 1st value and the 2nd value. Hence it can be positive, zero or negative. Syntax: public static int compare(char a, char b) Parameters: This method accepts
2 min read
Java Guava | Doubles.compare() method with Examples
Doubles.compare() method of Guava's Doubles Class is used to compare the two specified double values. These values are passed as the parameter and the result of comparison is found as the difference of 1st value and the 2nd value. Hence it can be positive, zero or negative. Syntax: public static int compare(double a, double b) Parameters: This meth
2 min read
Collator compare(Object, Object) method in Java with Example
The compare() method of java.text.Collator class is used to compare the strength of two objects and it will return 0, positive and negative value as an output according to the result . Syntax: public int compare(Object o1, Object o2) Parameter: This method takes two objects between which comparison is going to take place.Return Value: if the first
2 min read
Collator compare(String, String) method in Java with Example
The compare() method of java.text.Collator class is used to compare the strength of two string and it will return 0, positive and negative values as an output according to the result. Syntax: public abstract int compare(String source, String target) Parameter: This method takes two strings between which comparison is going to take place.Return Valu
2 min read
RuleBasedCollator compare() method in Java with Example
The compare() method of java.text.RuleBasedCollator class is used to compare the strength of two objects and it will return 0, positive and negative value as an output according to the result. Syntax: public int compare(Object o1, Object o2) Parameter: This method takes two objects between which comparison is going to take place.Return Value: if th
2 min read
How compare() method works in Java
Prerequisite: Comparator Interface in Java, TreeSet in JavaThe compare() method in Java compares two class specific objects (x, y) given as parameters. It returns the value: 0: if (x==y)-1: if (x < y)1: if (x > y)Syntax: public int compare(Object obj1, Object obj2)where obj1 and obj2 are the two objects to be compared using compare() method.
3 min read
Double compare() Method in Java with Examples
The compare() method of Double Class is a built-in method in Java that compares the two specified double values. The sign of the integer value returned is the same as that of the integer that would be returned by the function call. Syntax: public static int compare(double d1, double d2) Parameters: The function accepts two parameters: d1: The first
2 min read
How to Initialize and Compare Strings in Java?
String is one of the most basic data types and it is widely used in storing and manipulating pieces of text. One of the fundamental features of strings in Java is their immutability that is once a string is created, it will never be changed. Immutability creates two general ways of initialization with strings in Java using the String Pool. This art
5 min read
Difference Between Arrays.toString() and Arrays.deepToString() in Java
The deepToString() method of the Arrays class returns the string representation of the deep contents of the specified Object array. Unlike Arrays. toString(), if the array contains other arrays as elements, the string representation includes their contents, and so on. Arrays.toString(): Returns a string representation of the contents of the specifi
3 min read
Problem in comparing Floating point numbers and how to compare them correctly?
In this article, we will see what is the problem in comparing floating-point numbers and we will discuss the correct way to compare two floating-point numbers. What is the problem in comparing Floating-Point Numbers usually?Let us first compare two floating-point numbers with the help of relational operator (==).Example: Using "==" for comparison C
7 min read
How to Sort an Arrays of Object using Arrays.sort()
To sort the array of objects in both ascending and descending order in Java, we can use the Arrays.sort() method with the Comparator. In this article, we will learn how to sort an array of objects using Arrays.sort(). Sorting an Array of ObjectWith Array of Object what it really means is an array storing any type of object can be Integer, String or
3 min read
Java.util.Arrays.equals() in Java with Examples
Today we are going to discuss the simplest way to check whether two arrays are equal or not. Two arrays are considered equal if both arrays contain the same number of elements, and all corresponding pairs of elements in the two arrays are equal. In other words, two arrays are equal if they contain the same elements in the same order. Also, two arra
4 min read
Java.util.Arrays.deepEquals() in Java
Arrays.deepEquals() is used to check whether two arrays of single dimensional or multi-dimensional arrays are equal or not. It can compare two nested arrays (i.e. multidimensional array), irrespective of its dimension. Two array references are considered deeply equal if both are null, or if they refer to arrays that contain the same number of eleme
4 min read
Java.util.Arrays.copyOfRange() in Java
This method creates a copy of elements, within a specified range of the original array.Syntax : public static int[] copyOfRange(int[] original_array, int from_index, int to_index) original_array : Array to be copied fromfrom_index : Starting index of range to be copiedto_end : the final index of the range to be copied, exclusive. (This index may li
4 min read