Как сравнить два массива в Java?

Опубликовано: 15 Февраля, 2022

Predict the output of following Java program.

class Test
{
    public static void main (String[] args) 
    {
        int arr1[] = {1, 2, 3};
        int arr2[] = {1, 2, 3};
        if (arr1 == arr2) // Same as arr1.equals(arr2)
            System.out.println("Same");
        else
            System.out.println("Not same");
    }
}

Выход:

 Не то же самое 


В Java массивы - это объекты первого класса. В приведенной выше программе arr1 и arr2 - это две ссылки на два разных объекта. Итак, когда мы сравниваем arr1 и arr2, сравниваются две ссылочные переменные, поэтому мы получаем результат как «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 Arrays class for different primitive types (int, char, ..etc) and one for Object type (which is base of all classes in Java).

// we need to import java.util.Arrays to use Arrays.equals().
import java.util.Arrays;
class Test
{
    public static void main (String[] args) 
    {
        int arr1[] = {1, 2, 3};
        int arr2[] = {1, 2, 3};
        if (Arrays.equals(arr1, arr2))
            System.out.println("Same");
        else
            System.out.println("Not same");
    }
}

Выход:

 Тем же

How to Deep compare array contents?
As seen above, the Arrays.equals() works fine and compares arrays contents. Now the questions, what if the arrays contain arrays inside them or some other references which refer to different object but have same values. For example, see the following program.

import java.util.Arrays;
class Test
{
    public static void main (String[] args) 
    {
        // inarr1 and inarr2 have same values
        int inarr1[] = {1, 2, 3};
        int inarr2[] = {1, 2, 3};   
        Object[] arr1 = {inarr1};  // arr1 contains only one element
        Object[] arr2 = {inarr2};  // arr2 also contains only one element
        if (Arrays.equals(arr1, arr2))
            System.out.println("Same");
        else
            System.out.println("Not same");
    }
}

Выход:

 Не то же самое

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

import java.util.Arrays;
class Test
{
    public static void main (String[] args) 
    {
        int inarr1[] = {1, 2, 3};
        int inarr2[] = {1, 2, 3}; 
        Object[] arr1 = {inarr1};  // arr1 contains only one element
        Object[] arr2 = {inarr2};  // arr2 also contains only one element
        if (Arrays.deepEquals(arr1, arr2))
            System.out.println("Same");
        else
            System.out.println("Not same");
    }
}

Выход:

 Тем же

Как работает Arrays.deepEquals ()?
Он сравнивает два объекта, используя любые собственные методы equals (), которые у них могут быть (если у них есть метод equals (), реализованный кроме Object.equals ()). В противном случае этот метод будет рекурсивно сравнивать объекты поле за полем. При обнаружении каждого поля он будет пытаться использовать производный equals (), если он существует, в противном случае он продолжит рекурсию дальше.
Этот метод работает с циклическим графом объектов следующим образом: A-> B-> C-> A. У него есть обнаружение цикла, поэтому можно сравнивать ЛЮБЫЕ два объекта, и он никогда не войдет в бесконечный цикл (Источник: https://code.google.com/p/deep-equals/).

Exercise: Predict the output of following program

import java.util.Arrays;
class Test
{
   public static void main (String[] args) 
   {
      int inarr1[] = {1, 2, 3};
      int inarr2[] = {1, 2, 3}; 
      Object[] arr1 = {inarr1};  // arr1 contains only one element
      Object[] arr2 = {inarr2};  // arr2 also contains only one element
      Object[] outarr1 = {arr1}; // outarr1 contains only one element
      Object[] outarr2 = {arr2}; // outarr2 also contains only one element        
      if (Arrays.deepEquals(outarr1, outarr2))
          System.out.println("Same");
      else
          System.out.println("Not same");
    }
}

Пожалуйста, напишите комментарии, если вы обнаружите что-то неправильное, или вы хотите поделиться дополнительной информацией по теме, обсужденной выше

Вниманию читателя! Не переставай учиться сейчас. Ознакомьтесь со всеми важными концепциями Java Foundation и коллекций с помощью курса "Основы Java и Java Collections" по доступной для студентов цене и будьте готовы к работе в отрасли. Чтобы завершить подготовку от изучения языка к DS Algo и многому другому, см. Полный курс подготовки к собеседованию .