在此示例中,我们将使用ArraysUtilsApache Commons Lang库中的helper类来反转数组元素的顺序。反转数组元素顺序的ArrayUtils.reverse()方法是method。
ArrayUtils.reverse()方法被重载,以便我们能够逆转其它类型的数组,例如java.lang.Object,long,int,short,char,byte,double,float和boolean。
package org.nhooo.example.commons.lang; import org.apache.commons.lang3.ArrayUtils; public class ArrayReverseExample { public static void main(String[] args) { // 定义颜色数组。 String[] colors = {"Red", "Green", "Blue", "Cyan", "Yellow", "Magenta"}; System.out.println(ArrayUtils.toString(colors)); // 现在我们反转数组元素的顺序。 ArrayUtils.reverse(colors); System.out.println(ArrayUtils.toString(colors)); } }
这是上面代码片段的输出:
{Red,Green,Blue,Cyan,Yellow,Magenta} {Magenta,Yellow,Cyan,Blue,Green,Red}
Maven依赖
<!-- https://search.maven.org/remotecontent?filepath=org/apache/commons/commons-lang3/3.9/commons-lang3-3.9.jar --> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency>