gpt4 book ai didi

使用原生Java 和 apache commons实现数组反转

转载 作者:知者 更新时间:2024-03-12 08:00:32 27 4
gpt4 key购买 nike

这个例子将展示如何使用原生java 和 apache commons ArrayUtils.reverse 实现数组的反转。

初始化数据

String[] MONTHS_OF_YEAR_BACKWARDS;

@Before
public void setUp () {
    MONTHS_OF_YEAR_BACKWARDS = new String[] {
            "December",
            "November",
            "October",
            "September",
            "August",
            "July",
            "June",
            "May",
            "April",
            "March",
            "February",
            "January"
    };
}

原生Java实现

@Test
public void reverse_elements_in_array_with_java () {

    for (int i=0; i < MONTHS_OF_YEAR_BACKWARDS.length / 2; i++) {

        // set a temp variable for current element
        String temp = MONTHS_OF_YEAR_BACKWARDS[i];

        // find the last element - 1
        int j = MONTHS_OF_YEAR_BACKWARDS.length - i - 1;

        // set the first element to last
        MONTHS_OF_YEAR_BACKWARDS[i] = MONTHS_OF_YEAR_BACKWARDS[j];

        // set last to the first
        MONTHS_OF_YEAR_BACKWARDS[j] = temp;
    }

    logger.info(Arrays.toString(MONTHS_OF_YEAR_BACKWARDS));

    assertEquals("May", MONTHS_OF_YEAR_BACKWARDS[4]);
}

输出

[January, February, March, April, May, June, July, August, September, October, November, December]

Apache Commons实现

@Test
public void reverse_elements_in_array_with_apache_commons () {

    ArrayUtils.reverse(MONTHS_OF_YEAR_BACKWARDS);

    logger.info(Arrays.toString(MONTHS_OF_YEAR_BACKWARDS));

    assertEquals("May", MONTHS_OF_YEAR_BACKWARDS[4]);
}

输出

[January, February, March, April, May, June, July, August, September, October, November, December]

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com