PresFelber
PresFelber

Reputation: 61

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

Upvotes: 1

Views: 267

Answers (2)

geanakuch
geanakuch

Reputation: 972

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

Upvotes: 2

user14940971
user14940971

Reputation:

Since Java 9 you can use IntStream.iterate and Arrays.compare methods:

public static String[] backwards(String[] array) {
    return IntStream.iterate(array.length - 1, i -> i >= 0, i -> i - 1)
            .mapToObj(i -> array[i])
            .toArray(String[]::new);
}
public static boolean isPalindrome(String[] array) {
    return Arrays.compare(array, backwards(array)) == 0;
}
// test
public static void main(String[] args) {
    String[] arr = {"backwards", "palindrome", "abracadabra", "abcdcba"};

    System.out.println(isPalindrome(arr)); // false
    System.out.println(isPalindrome(arr[3].split(""))); // true
}

Upvotes: 1

Related Questions