baked182 baked182 - 1 month ago 17
Java Question

Method for equal arrays

beginner here!

I am trying to write a boolean method that returns

true
if the two arrays a and b have exactly the same elements in the same order, and
false
otherwise.

Although, I am having a problem with comparing two null arrays, for which i want it to return true if:

int [] A = { };

int [] B = { };


My code so far is:

public static boolean equalArrays(int [] a, int [] b) {
if(a.length == 0 && b.length == 0)
return true;
else {
if(a.length == b.length)
for(int i = 0; i < a.length ; i++)
if (a[i] == b[i])
return true;
}
return false;
}


EDIT1: Fixed the code above

EDIT2: Another problem is when i try testing

int [] A = {2, 3, 4, 5, 6};
int [] B = {2, 3, 4, 6, 5};


It returns true when it is supposed to return false. Anyone have any idea on where the problem is?

Answer

The issue is inside your for loop. It should be:

public static boolean equalArrays(int [] a, int [] b) {
    if(a == b){
        return true;
    }

    if(null == a || null == b){
        return false;
    }

    if(a.length != b.length){
        return false;
    }

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

    return true;
}

Note that I swapped the places of true and false and now check for != instead of == That's because we want all elements to be equal, not only a few of them.

As BackSlash commented, I added checks for null

PS: You should use brackets -> it makes the code much more readable