Comparing Arrays in JAVA


Comparing Arrays

When we create array objects, they are created in memory at some memory address. Each array that is created is assigned different address.  So, when we compare the array objects with == operators, their memory location get compared. So, they will never be equal even when they have the same values assigned to them.  Same is the case when we compared string objects.

Wrong way of comparing / Common mistake / Never compare arrays with ==

package com.example;
public class arrays
{

public static void main(String[] args)
{

int []numbers1 ={2,4,6,8,10};
int []numbers2 ={2,4,6,8,10};
if (numbers1 == numbers2)
{

System.out.println(“they are the same”);

}
else
{

System.out.println(“they are not the same”);

}

}

}

So, we cannot compare the two array objects with == operators, because that will compare the memory locations rather than the values.

Now suppose you copied one array into another as given, then both array will point to the same array then compare with == operators will give two arrays are same, because both are pointing to the same single address. See.

int []numbers1={2,4,6,8,10};

int []number2 = number1

if(number1==number2) {

System.out.println(“The two arrays are the same”);

}

else

{

System.out.println(“The two arrays are not the same”);

}

The output will be two arrays are same. This will be true because we have copied address of array number1 into memory location for array number2. Numbers1 and numbers2 are pointing exactly at the same place.

Correct way of comparing arrays

The correct way is to compare two array objects is element by element.

Steps-1: declare arrayEqual of type Boolean and make it initially true

Step-2: Compare arraylengths with !=; if not equal set arrayEqual to false

Step-3: In the while loop test arrayEqual && i < numbers1.length i.e. if arrayEqual is true and i is within length

Step-4: test elements of array, if any element is not equal, make arrayEqual to false

Step-5: two arrays are equal only if arrayEqual is true

Here is complete program to compare two arrays

package com.example;
public class arrays
{

public static void main(String[] args)
{

int[] numbers1 = {2, 4, 6, 8, 10};
int[] numbers2 = {2, 4, 6, 8, 1};
boolean arrayEqual = true; //unless we proove it be false
int i = 0;
//step-1 to check if two arrays are of same size
if (numbers1.length != numbers2.length)

{

arrayEqual = false;

}
//step-2 if length same then compare element wise; if arrayEqual is false it will never enter into this loop
while (arrayEqual && i < numbers1.length)

{

if (numbers1[i] != numbers2[i])

{

arrayEqual = false;

}

i++;

}

if (arrayEqual)

{

System.out.println(“They are same”);

}

else

{

System.out.println(“They are not same”);

}

}

}

This program prints correct result, if every element of two arrays is same then two arrays are equal else two arrays are not equal.

error: Content is protected !!