ArrayUtils 工具类常用方法

102 阅读1分钟

工具类:org.apache.commons.lang3.ArrayUtils
版本:commons-lang3:3.7
地址:ArrayUtils API
说明:ArrayUtils 是专门用来处理数组的工具类,每种类型的方法都包括8中原生数据类型和包装类型,以及ObjectClassStringCharacter等。可以优雅地处理空输入,而不会抛出异常,因此不必再判断一次是否为null。

swap函数交换元素

public class SwapExample {
    public static void main(String[] args) {
        Integer[] array = {1, 2, 3};
        int index1 = 0;
        int index2 = 2;

        // 使用Apache Commons Lang3库中的ArrayUtils进行交换
        ArrayUtils.swap(array, index1, index2);

        // 输出交换后的数组
        for (Integer i : array) {
            System.out.println(i);
        }
    }
}

手写的实现方式:

private void swap(int[] nums, int i, int j) {
    int temp = nums[i];
    nums[i] = nums[j];
    nums[j] = temp;
}

实现上有很多重载方法,截图如下:

image.png

JDK中Collections也有一个静态swap函数。

isEmpty方法判段数组长度为0或NULL

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtilsPrimitiveExample {
    public static void main(String[] args) {
        int[] emptyIntArray = {};
        int[] nullIntArray = null;
        int[] nonEmptyIntArray = {1, 2, 3};

        System.out.println("Is emptyIntArray empty? " + ArrayUtils.isEmpty(emptyIntArray)); // true
        System.out.println("Is nullIntArray empty? " + ArrayUtils.isEmpty(nullIntArray)); // true
        System.out.println("Is nonEmptyIntArray empty? " + ArrayUtils.isEmpty(nonEmptyIntArray)); // false
    }
}

运行结果:

Is emptyIntArray empty? true
Is nullIntArray empty? true
Is nonEmptyIntArray empty? false

支持其他基本类型和对象数组:

image.png