leslie
leslie

Reputation: 15

Looping through two arrays to check if equal

Trying to check if two arrays are equal, meaning same length and same elements in positions.

I've tried Arrays.equals(1,2) but it's still coming out as false, while it needs to be coming out as true.

I've tried to create a nested for loop to check each index but I am still getting false.

My code:

public boolean equals(double[] s) //for loop checking each element
{
    if (s==null)
    {
        return false;
    }
    for (int i=0;i<data.length;i++)
    {
        for(int j=0;j<s.length;j++)
        {
            if (data[i]!=s[j])
            {
                return false;
            }
        }
    }
    return true;

}

Upvotes: 1

Views: 14978

Answers (4)

Harry Blargle
Harry Blargle

Reputation: 426

if you want to see if they have the same elements but you don't care if they have the same order, sort them first.

Arrays.sort(data);
Arrays.sort(s);
return Arrays.equals(data,s);

Upvotes: 2

wns349
wns349

Reputation: 1306

You don't need a nested loop to check the elements. In fact, your code is wrong in a sense that it's checking all the elements from one array to another.

You might want to

// Check to make sure arrays have same length
if (data.length != s.length) 
   return false;

for (int i=0;i<data.length;i++)
{
    if (data[i]!=s[i])
    {
       return false;
    }
}
return true;

Upvotes: 1

Bohemian
Bohemian

Reputation: 425448

Don't reinvent the wheel!

public boolean equals(double[] s) {
    return Arrays.equals(s, data);
}

Arrays.equals() compares array lengths and each element.

Upvotes: 11

Butani Vijay
Butani Vijay

Reputation: 4239

You can use as below :

if(arr1.length!=arr2.length) 
   return false;

for(int index=0;index<arr1.length;index++)
{
    if (arr1[index]!=arr2[index])
         return false;

}
return true;

Upvotes: 0

Related Questions