java Arrays方法使用介绍


本文中的方法采用的是jdk11的版本

sort

形式参数要求

  1. 输入一个数组(可以是int,short,long,byte,float,double,char类型的数组)
  2. 输入一个数组,并且输入要排序的下标范围,其中左下标进入排序右下标不进入排序。

数组还可以时Object以及泛型,但是在泛型对应的类中必须实现Comparator比较器,Object必须实现comparable接口

结果
作为形式参数输入的数组(或者数组的某一部分)将升序排序

代码例子

public static void main(String[] args) {
		//定义一个数组test
        int[] test ={6,5,4,3,2,1};
        //数组排序
        Arrays.sort(test);
        for (int temp:test) {
            System.out.print(temp);//最终结果输出123456
        }
    }
 public static void main(String[] args) {
		//定义一个数组test
        int[] test ={6,5,4,3,2,1};
        //数组排序
        Arrays.sort(test,0,4);
        for (int temp:test) {
            System.out.print(temp);//输出345621
        }
    }

parallelSort

形式参数要求
与sort相同
结果
与sort相同
与sort的区别
当数据量很小的时候使用sort与parallelSort的速度相差不大
当数据量开始增加的时候sort比parallelSort快一点
数据量持续变大,到一个临界点之后,parallelSort将比sort更快

所以 数据量小使用sort排序,不要使用parallelSort排序,数据量大使用parallelSort排序。

代码例子

public static void main(String[] args) {
        int[] test ={6,5,4,3,2,1};
        Arrays.parallelSort(test,0,4);
        for (int temp:test) {
            System.out.print(temp);//输出345621
        }
        System.out.println();
        Arrays.sort(test);
        for (int temp:test) {
            System.out.print(temp);//输出123456
        }
    }

parallelPrefix

形式参数要求

public static <T> void parallelPrefix​(T[] array, BinaryOperator<T> op)
public static <T> void parallelPrefix​(T[] array, int fromIndex, int toIndex, BinaryOperator<T> op)

这里的泛型可以替换成double long int类型的数组,后面的 BinaryOperator是一种关联函数,用来执行叠加或者其他操作
结果
根据下面的代码例子,它的执行顺序为将数组中的每一个元素按照后面的函数执行并实时保存
代码例子

 		int[] test2 ={1,2,3,4,5,6};
        Arrays.parallelPrefix(test2, new IntBinaryOperator() {
            @Override
            public int applyAsInt(int left, int right) {
                return left+right;
            }
        });
        for (int temp:test2) {
            System.out.print(temp + " ");//输出1 3 6 10 15 21
        }

binarySearch

形式参数要求

public static int binarySearch​(long[] a, long key)
public static int binarySearch​(long[] a, int fromIndex, int toIndex, long key)

除了long类型的数组之外,还可以是int short char byte double float
除此之外,数组一定要是排过序的,不然二分查找无法实行
结果
如果是排过序的,并且数组中有寻找的对应值,那么返回对应值的下标,如果没有对应值则返回一个负数,如果是无序的,返回值啥都可能有,不靠谱。
代码例子

		int[] test2 ={1,2,3,4,5,6,8};
        int num = Arrays.binarySearch(test2,3);
        int num2 = Arrays.binarySearch(test2,7);
        System.out.println("num = " + num);//num = 2
        System.out.println("num2 = " + num2);//num2 = -7

        int[] test3 = {2,1,3,5,9,8};//如果是无序的
        int num3 = Arrays.binarySearch(test3,8);
        System.out.println("num3 = " + num3);//num3 = -5

equals

形式参数要求

public static boolean equals​(long[] a, long[] a2)
public static boolean equals​(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)

除了long类型的数组之外还可以是int short char byte boolean double float Object 或者泛型,对应的泛型和Object需要有比较器
结果
返回布尔类型变量,如果长度相等并且每一个数据都相等则返回true 值得说的是 如果两个都是null也会返回true

通过源码我们可以知道它是通过mismatch来比较的,这个方法接下来也会提到。
代码例子

		int[] test1 = {1,2,3,4,5};
        int[] test2 = {1,2,3,4};
        int[] test3 = {1,2,3,4};
        int[] test4 = {1,2,3,5};

        System.out.println(Arrays.equals(test1,test2));//false
        System.out.println(Arrays.equals(test2,test3));//true
        System.out.println(Arrays.equals(test2,test4));//false

fill

形式参数要求

public static void fill​(int[] a, int val)
public static void fill​(int[] a, int fromIndex, int toIndex, int val)

除了int还可以是 long short char byte boolean double float Object。
结果
将整个数组或者数组的指定内容换成val。
源码如下;

public static void fill(int[] a, int val) {
        for (int i = 0, len = a.length; i < len; i++)
            a[i] = val;
    }

代码例子

        int[] test1 = {1,2,3,4,5};

        Arrays.fill(test1,3);
        for (int a:test1) {
            System.out.print(a);//33333
        }

copyOf

形式参数要求

public static int[] copyOf​(int[] original, int newLength)

除了int之外还可以是 long double float short byte char boolean类型
结果
得到一个新的数组,在复制了original数组中的元素之后,长度还变为newLength
如果长度变长,则填充默认数据
如果长度变短,多的数据就没了
源码:

    public static int[] copyOf(int[] original, int newLength) {
        int[] copy = new int[newLength];
        System.arraycopy(original, 0, copy, 0,
                         Math.min(original.length, newLength));
        return copy;
    }

代码例子

        int[] test1 = {1,2,3,4,5};

        int[] test2 = Arrays.copyOf(test1,10);
        for (int a:test2) {
            System.out.print(a);//1234500000
        }
        System.out.println();
        int[] test3 = Arrays.copyOf(test1,3);
        for (int a:test3) {
            System.out.print(a);//123
        }

copyOfRange

形式参数要求

public static int[] copyOfRange​(int[] original, int from, int to)

还可以是byte short long double float boolean char以及泛型
结果
返回一个数组,并且拥有给定数组的指定范围的数据。
源码如下:

    public static int[] copyOfRange(int[] original, int from, int to) {
        int newLength = to - from;
        if (newLength < 0)
            throw new IllegalArgumentException(from + " > " + to);
        int[] copy = new int[newLength];
        System.arraycopy(original, from, copy, 0,
                         Math.min(original.length - from, newLength));
        return copy;
    }

可以发现和copyOf的代码差别不大
代码例子

        int[] test1 = {1,2,3,4,5};

        int[] test2 = Arrays.copyOfRange(test1,0,2);
        for (int a:test2) {
            System.out.print(a);//12
        }
        System.out.println();
        int[] test3 = Arrays.copyOfRange(test1,0,10);
        for (int a:test3) {
            System.out.print(a);//1234500000
        }

asList

形式参数要求

public static <T> List<T> asList​(T... a)

结果
将列表中的参数放到集合中,返回一个List集合。
代码例子

        List<String> arr = Arrays.asList("q","w","e","r");
        for (String a :arr) {
            System.out.print(a);//qwer
        }

hashCode

形式参数要求

public static int hashCode​(int[] a)

参数还可以是byte short long float double boolean char以及Object的数组
结果
返回数组的哈希码
代码例子

        int[] test = {1,2,3};
        int a = Arrays.hashCode(test);
        System.out.println(a);//a为test的hashcode

deepHashCode

形式参数要求

public static int deepHashCode​(Object[] a)

结果
返回Object数组的深度哈希码。
代码例子

        int[] test = {1,2,3};
        byte[] test2 = {1,2,3,4};
        Object[] test3 = {test,test2};
        int b = Arrays.deepHashCode(test3);
        int a = Arrays.hashCode(test3);
        System.out.println(a);//a为test3的hashcode  1405667972
        System.out.println(b);//b为test3的deepHashCode  1911619

deepEquals

形式参数要求

public static boolean deepEquals​(Object[] a1, Object[] a2)

结果
深度比较两个数组是否相同,与equals不同的是,deepEquals能够比较多维数组的内容。
代码例子

        int[][] test1 = {{1,2,3},{2,3,4},{3,4,5}};
        int[][] test2 = {{1,2,3},{2,3,4},{3,4,5}};
        System.out.println(Arrays.equals(test1,test2));//false
        System.out.println(Arrays.deepEquals(test1,test2));//true

toString

形式参数要求

public static String toString​(int[] a)

参数还可以是byte short long float double boolean char Object类型的数组
结果
按标准返回数组中的数据
源码如下:

    public static String toString(int[] a) {
        if (a == null)
            return "null";
        int iMax = a.length - 1;
        if (iMax == -1)
            return "[]";

        StringBuilder b = new StringBuilder();
        b.append('[');
        for (int i = 0; ; i++) {
            b.append(a[i]);
            if (i == iMax)
                return b.append(']').toString();
            b.append(", ");
        }
    }

代码例子

        int[] test = {2,3,4,5,6};
        String[] test2 = {"qqq","www","eee"};
        System.out.println(Arrays.toString(test));//[2, 3, 4, 5, 6]
        System.out.println(Arrays.toString(test2));//[qqq, www, eee]

deepToString

形式参数要求

public static String deepToString​(Object[] a)

结果
适用于多维数组的toString。
代码例子

        int[][] test = {{2,3,4,5,6},{1,2,3},{2,3}};
        System.out.println(Arrays.toString(test));//[[I@7c30a502, [I@49e4cb85, [I@2133c8f8]
        System.out.println(Arrays.deepToString(test));//[[2, 3, 4, 5, 6], [1, 2, 3], [2, 3]]

setAll

形式参数要求

public static void setAll​(int[] array, IntUnaryOperator generator)

参数还可以是泛型 long double。
结果
按照对应的函数要求填充数字。
源码:

    public static void setAll(int[] array, IntUnaryOperator generator) {
        Objects.requireNonNull(generator);
        for (int i = 0; i < array.length; i++)
            array[i] = generator.applyAsInt(i);
    }

代码例子

        int[] test = new int[3];
        Arrays.setAll(test, new IntUnaryOperator() {
            @Override
            public int applyAsInt(int operand) {
                return 1;
            }
        });
        for (int a:test) {
            System.out.print(a);//111
        }

parallelSetAll

形式参数要求

public static void parallelSetAll​(int[] array, IntUnaryOperator generator)

参数还可以是泛型 long double。
结果
结果和setAll差不多,都是为数组填充数据,但是从源码看他们又有些不同,只是我看不出来…
源码:

    public static void parallelSetAll(int[] array, IntUnaryOperator generator) {
        Objects.requireNonNull(generator);
        IntStream.range(0, array.length).parallel().forEach(i -> { array[i] = generator.applyAsInt(i); });
    }

代码例子

        int[] test = new int[3];
        Arrays.setAll(test, new IntUnaryOperator() {
            @Override
            public int applyAsInt(int operand) {
                return 1;
            }
        });
        for (int a:test) {
            System.out.print(a);//111
        }
        System.out.println();

        Arrays.parallelSetAll(test, new IntUnaryOperator() {
            @Override
            public int applyAsInt(int operand) {
                return 0;
            }
        });
        for (int a:test) {
            System.out.print(a);//000
        }

spliterator

形式参数要求

public static Spliterator.OfInt spliterator​(int[] array)
public static Spliterator.OfInt spliterator​(int[] array, int startInclusive, int endExclusive)

泛型,long, double都可以
结果
返回覆盖所有指定数组的Spliterator(可拆分迭代器)。
代码例子

        int[] test = {1,2,3};
        Spliterator<Integer> test2 = Arrays.spliterator(test);
        System.out.println(test2.characteristics());//17488 不知道为什么是这个数但是感觉很厉害!

stream

形式参数要求

public static IntStream stream​(int[] array)
public static IntStream stream​(int[] array, int startInclusive, int endExclusive)

还可以是泛型 long double 类型。
结果
首先对于stream,它是一种高级迭代器,可以为他执行一些操作
这个Stream方法就是把数组中的数据或者指定范围的数据放入流中
注意stream终端操作后就不能再使用了。
代码例子

        int [] test = {1,5,99};
        IntStream test2 = Arrays.stream(test);
        //System.out.println(test2.max());  //99 如果不注释这一行会告诉你流已经使用
        System.out.println(test2.count());//3 显示的是test2流中的个数

compare

形式参数要求

public static int compare​(boolean[] a, boolean[] b)
public static int compare​(boolean[] a, int aFromIndex, int aToIndex, boolean[] b, int bFromIndex, int bToIndex)

参数还可以是byte int short long float double 泛型,其中泛型需要有比较器
结果
返回第一个不相等的元素的差值,如果两个数组完全相等,返回0,如果一个数组a比另一个数组b长度短,但是b中的数据与a完全相同直到a没有数据,此时返回a b的数组长度的差值。
源码:

    public static int compare(byte[] a, byte[] b) {
        if (a == b)
            return 0;
        if (a == null || b == null)
            return a == null ? -1 : 1;

        int i = ArraysSupport.mismatch(a, b,
                                       Math.min(a.length, b.length));
        if (i >= 0) {
            return Byte.compare(a[i], b[i]);
        }

        return a.length - b.length;
    }

代码例子

        byte[] test1 = {1,2,3};
        byte[] test2 = {1,2,4};
        
        System.out.println(Arrays.compare(test1,test2));//-1
        System.out.println(Arrays.compare(test2,test1));//1
        System.out.println(Arrays.compare(test1,test1));//0

        byte[] test3 = {12,13,14};
        System.out.println(Arrays.compare(test1,test3));//-11

另一个例子

        byte[] test1 = {1,2,3,5,6,8};
        byte[] test2 = {1,2,3,5};

        System.out.println(Arrays.compare(test1,test2));//2
        System.out.println(Arrays.compare(test2,test1));//-2

compareUnsigned

形式参数要求
只能是整数类型

public static int compareUnsigned​(long[] a, int aFromIndex, int aToIndex, long[] b, int bFromIndex, int bToIndex)
public static int compareUnsigned​(long[] a, long[] b)

结果
compare的无符号版

代码例子

        byte[] test1 = {1,2,3,-5};
        byte[] test2 = {1,2,3,5};

        System.out.println(Arrays.compare(test1,test2));//-10
        System.out.println(Arrays.compare(test2,test1));//10
        System.out.println(Arrays.compareUnsigned(test1,test2));//246 值为-5 与 5无符号值之差

        byte a1 = -5;
        byte a2 = 5;
        System.out.println(Byte.toUnsignedInt(a1));//251
        System.out.println(Byte.toUnsignedInt(a2));//5

mismatch

形式参数要求

public static int mismatch​(int[] a, int[] b)
public static int mismatch​(int[] a, int aFromIndex, int aToIndex, int[] b, int bFromIndex, int bToIndex)

可以是short byte long double float boolean char
结果
返回第一个不相同的下标,如果相同就返回-1
源码:

    public static int mismatch(byte[] a, byte[] b) {
        int length = Math.min(a.length, b.length); // Check null array refs
        if (a == b)
            return -1;

        int i = ArraysSupport.mismatch(a, b, length);
        return (i < 0 && a.length != b.length) ? length : i;
    }

ArraysSupport.mismatch的源码:

public static int mismatch(byte[] a,
                               byte[] b,
                               int length) {
        // ISSUE: defer to index receiving methods if performance is good
        // assert length <= a.length
        // assert length <= b.length

        int i = 0;
        if (length > 7) {
            if (a[0] != b[0])
                return 0;
            i = vectorizedMismatch(
                    a, Unsafe.ARRAY_BYTE_BASE_OFFSET,
                    b, Unsafe.ARRAY_BYTE_BASE_OFFSET,
                    length, LOG2_ARRAY_BYTE_INDEX_SCALE);
            if (i >= 0)
                return i;
            // Align to tail
            i = length - ~i;
//            assert i >= 0 && i <= 7;
        }
        // Tail < 8 bytes
        for (; i < length; i++) {
            if (a[i] != b[i])
                return i;
        }
        return -1;
    }

代码例子

        byte[] test1 = {1,2,3,-5};
        byte[] test2 = {1,2,3,5};
        byte[] test3 = {1,2,3};
        byte[] test4 = {1,2,3,-5};
        byte[] test5 = {1,2,3,-5,6};

        System.out.println(Arrays.mismatch(test1,test2));//3
        System.out.println(Arrays.mismatch(test1,test3));//3
        System.out.println(Arrays.mismatch(test1,test4));//-1
        System.out.println(Arrays.mismatch(test1,test5));//4

以上就是Arrays的所有方法介绍了!

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值