数组

来源:互联网 发布:语音网络系统如何注册. 编辑:程序博客网 时间:2024/05/17 17:40

数组复制的方法

  1. for循环复制

  2. Arrays.copyOf(original, newLength);

    源数组 新数组长度

     
    int[] srcArray = {1,2,3,4,5,6};
    int[] newArray = Arrays.copyOf(srcArray, 10);
    // [1, 2, 3, 4, 5, 6, 0, 0, 0, 0]

    新长度大于源数组时,显示为类型初始化的值。int->0 String->null

  3. System.arraycopy(src, srcPos, dest, destPos, length);

    源数组 | 起始索引|目标数组|起始位置|长度

     
    int[] srcArray = {1,2,3,4,5,6};
    int[] newArray = new int[srcArray.length];
    System.arraycopy(srcArray, 1, newArray, 0, 3);
    [2, 3, 4, 0, 0, 0]

    Arrays.copyOf 的底层实现也是通过System.arraycopy

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

ARRAYS工具类

  • Arrays.toString(int[] a)

    ​int[] scores = { 3, 4, 7, 12, 43, 5,10, 6,1 };

    ​String s = Arrays.toString(scores);//数组转字符串表达

    ​System.out.println(s);

    ​//将输出:[3, 4,7, 12, 43, 5, 10, 6, 1]

  • Arrays.sort(int[] a)

    ​Arrays.sort(scores);//对scores数组升序排列

  • Arrays.fill(scores,5);

    ​int[] scores = { 3, 4, 7, 12, 43, 5,10, 6,1 };

    ​Arrays.fill(scores, 5);//将数组的所有值 替换成  5

    ​System.out.println(Arrays.toString(scores));

    ​//将输出:[5, 5,5, 5, 5, 5, 5, 5, 5]

原创粉丝点击