Search code examples
javaarrayspalindrome

Creating a method to reverse an array String[] and then checking if it is a palindrome


I had to create two methods. One to take an array of Strings and reverse their order. Using assertArrayEquals to test, the backwards method passed. Then I had to create a method to check if a String array is a palindrome, but that test if failing. I thought that maybe I messed something up in the backwards method, but I tested that 12 different ways. I may be really tired, but what did I do wrong here?

public static String[] backwards(String[] array) {
    for (int index = 0; index < array.length / 2; index++) {
        String string = array[index];
        array[index] = array[array.length - index - 1];
        array[array.length - index - 1] = string;
    }
    return array;
}

public static boolean isPalindrome(String[] array) {
    if (array == backwards(array)) {
        return true;
    }
    return false;
}

Solution

  • There are two things wrong with this code:

    #1 You are editing the array in place. So the backwards method does not only return a reversed array, it changes the original array.

    #2 You are comparing two arrays with == which will check if it's the same instance. You can use Arrays.equals instead.

    public static String[] backwards(String[] array) {
        String[] resArray = new String[array.length];
        for (int index = 0; index < array.length; index++) {
            resArray[index] = array[array.length - index - 1];
        }
        return resArray;
    }
    
    public static boolean isPalindrome(String[] array) {
        return Arrays.equals(array, backwards(array));
    }