Array工具类

来源:互联网 发布:java文件读写 编辑:程序博客网 时间:2024/05/21 19:38

//定义一个 a 数组,使用静态初始化

    int[] a = new int[]{3, 4, 5, 6};

    //定义一个 b 数组, 使用静态初始化

    int[] b = new int[]{3, 4, 5, 6};


    //使用 Arrays类的 equals方法.

    //boolean equals(type[] a, type[] b)如果 a数组 b数组长度相等,元素依次相同,则会返回 true

    //如果 a 数组 b 数组 长度相等, 每个元素依次相等, 将会输出 true

    System.out.println("a 数组 b数组 是否相等呢?" + Arrays.equals(a, b));


    //使用 Arrays类的 copyOf方法.

    //type[] copyOf(type[] original, int length)

    //这个方法会把 original(原件)数组复制成一个新数组,其中 length 是新数组的长度.

    //如果 length 小于 original 数组的长度, 新数组就是原数组前面 length个元素.

    //如果 length大于 original数组的长度, 新数组前面元素就是原数组的所有元素,

    //后面补充 0(数值类型) / false(布尔类型) / null(引用类型)看原数组是啥类型.

    //复制 a 数组, 生成一个 a2 数组, 然后对比是否相等

    int[] a2 = Arrays.copyOf(a, 6);

    System.out.println("a 数组 a2 数组 是否相等呢?" + Arrays.equals(a, a2));


    //使用 Arrays类的 toString方法

    //String toString(type[] a)

    //该方法将一个数组转换成一个字符串进行输出.该方法按照顺序把多个数组元素连起来,

    //多个数组元素之间使用英文逗号, 和空格隔开.

    //输出 a2 数组

    System.out.println("a2 数组的元素为:" + Arrays.toString(a2));


    //使用 Arrays 类的 fill 方法

    //void fill(type[]a, type val)该方法将会把 a数组的所有元素都赋值为 val

    //void fill(type[]a, int formIndex, int toIndex, type val)

    //该方法和上面方法作用相同, 区别是将数组a fromIndex toIndex索引处的数组元素赋值为 val

    // a2 数组的第 3个元素(包括) 到第 5个元素(不包括)赋值为 1

    Arrays.fill(a2, 2, 4, 1);

    //输出 a2 数组元素看看

    System.out.println("a2 数组的元素为:" + Arrays.toString(a2));


    //使用 Arrays 类的 sort 方法

    //void sort(type[] a)该方法对数组a 的元素进行排序.

    //void sort(type[] a, int formIndex, int toIndex)该方法和上面方法类似,区别是

    //仅仅对 fromIndex toIndex 索引的元素进行排序.

    // a2 数组进行排序

    Arrays.sort(a2);

    //输出 a2 数组

    System.out.println("a2 数组的元素为:" + Arrays.toString(a2));


    //使用二分搜索法来搜索制定的char型数组,以获得指定的值。

    Arrays.binarySearch( [] a,item key)

            //a - 要搜索的数组

fromIndex - 要搜索的第一个元素的索引(包括)
toIndex - 要搜索的最后一个元素的索引(不包括)
key - 要搜索的值

    Arrays.binarySearch( [] a,int fromIndex,int toIndex,item key)


     //将指定数组的指定范围复制到一个新数组。该范围的初始索引 (from) 必须位于 0 和 original.length(包括)之间。original[from] 处的值放入副本的初始元素中(        除非 from == original.length 或 from == to)。原数组中后续元素的值放入副本的后续元素。该范围的最后索引 (to) (必须大于等于 from)可以大  于 original.length,在这种情况下,false 被放入索引大于等于 original.length - from 的副本的所有元素中。返回数组的长度为 to - from

   Arrays.copyOfRange([] original,int from,int to);


  //基于指定数组的内容返回哈希码。对于任何两个满足 Arrays.equals(a, b) 的 boolean 型数组 a 和 b,也可以说 Arrays.hashCode(a) ==           Arrays.hashCode(b)

  此方法返回的值与在 List 上调用 hashCode 方法获得的值相同,该 List 包含以相同顺序表示 a 数组元素的 Boolean 实例的序列。如果 a 为 null,则此方法返回 0。

     Arrays.hashCode([] a);


    



  

原创粉丝点击