Java Arrays 工具类

导包:java.util.Arrays

常用方法列表:

  • public static void sort(Object[] a)

    对数组按照升序排序

    注:Object 泛指 7 种基本数据类型(没有boolean)

  • public static void sort(Object[] a, Object fromIndex, Object toIndex)

    对数组元素指定范围进行排序,排序范围:[ fromIndex, toIndex )

    注:Object 泛指 7 种基本数据类型(没有boolean)

  • public static void fill(Object[] a, Object val)

    为数组元素填充相同的 object

    注:Object 泛指 7 种基本数据类型(没有boolean)

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

    对数组的部分元素填充一个值,填充范围:[ fromIndex, toIndex )

    注:Object 泛指 7 种基本数据类型(没有boolean)

  • public static String toString(Object[] a)

    返回数组的字符串形式

    注:Object 泛指 8 种基本数据类型和 Object 类型

    源码如下:

    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(", ");
    }
    

    输出示例:

    [2, 5, 0, 4, 1, -10]
    
  • public static String deepToString(Object[] a)

    返回多维数组的字符串形式

    示例:

    int[][] nums = {{1,2}, {3,4}};
    System.out.println(Arrays.deepToString(nums));
    /*
     * 结果:[[1, 2], [3, 4]]
     */
    
  • public static int binarySearch(Object[] a, Object key)

    从数组中使用二分查找元素,返回元素下标

    前提是数组已排序,不存在时返回负数,表示该元素最有可能存在的位置索引

    注:Object 泛指 7 种基本数据类型(没有boolean)和 Object 类型

  • public static int binarySearch(Object[] a, int fromIndex, int toIndex, Object key)

    从数组中使用二分查找元素,返回元素下标,查找范围:[ fromIndex, toIndex )

    前提是数组已排序,不存在时返回负数,表示该元素最有可能存在的位置索引

    注:Object 泛指 7 种基本数据类型(没有boolean)和 Object 类型

  • public static boolean equals(Object[] a, Object[] a2)

    两个数组是否相等

    注:Object 泛指 8 种基本数据类型和 Object 类型

    源码:

    if (a==a2)
    	return true;
    if (a==null || a2==null)
    	return false;
    
    int length = a.length;
    if (a2.length != length)
    	return false;
    
    for (int i=0; i<length; i++)
        // 不同类型的数据 if 里的条件不同
    	if (a[i] != a2[i])
    		return false;
    
    return true;
    
  • public static int[] copyOf(int[] original, int newLength)

    从原数组的起始位置开始复制,复制的长度是 newlength 。只能从原数组的起始位置开始复制。

    注:此处 int 可换成其他基本数据类型

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

    复制数组,复制范围:[ from, to )

    注:此处 int 可换成其他基本数据类型

发布了39 篇原创文章 · 获赞 83 · 访问量 5519

猜你喜欢

转载自blog.csdn.net/siriusol/article/details/104739723