Question

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;

}
Était-ce utile?

La solution 3

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;

Autres conseils

Don't reinvent the wheel!

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

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

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);

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;
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top