程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

暂无数据

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

发布于2022-09-29 22:06     阅读(1123)     评论(0)     点赞(23)     收藏(1)


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

解决方案


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


所属网站分类: 技术文章 > 问答

作者:黑洞官方问答小能手

链接:http://www.javaheidong.com/blog/article/525012/bb8e87cae5d88cbec8f3/

来源:java黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

23 0
收藏该文
已收藏

评论内容:(最多支持255个字符)