Arrays
java.util.Arrays
是Java提供的针对数组的工具类。
方法
Arrays主要分为以下几种类型的方法:
将数组转换为List
二分法查找元素在数组中的索引
拷贝数组
比较数组
数组排序
填充数组
根据数组生成hashCode
将数组转换为字符串
数组->List
返回一个受指定数组支持的固定大小的列表。
示例
执行代码:
结果:
这是因为,asList返回的实例的类型不是java.util.ArrayList
,而是Arrays的内部类ArrayList
,这个类同样继承AbstractList
,但是此类被设计为固定大小的List,没有实现add等方法。
源码如下:
数组拷贝
System.arrayCopy
本地方法已经可以完成数组的拷贝,但是传入的类型为Object[],得到的类型Object[] 有可能造成类型转换异常等问题,而且传入参数过多,不便使用。所以,在Arrays中又提供了Arrays.copyOf
和Arrays.copyOfRange
方法,更方便完成数组操作。
基本类型:
static boolean[] copyOf(boolean[] original, int newLength)
static byte[] copyOf(byte[] original, int newLength)
static char[] copyOf(char[] original, int newLength)
static short[] copyOf(short[] original, int newLength)
static int[] copyOf(int[] original, int newLength)
static long[] copyOf(long[] original, int newLength)
static float[] copyOf(float[] original, int newLength)
static double[] copyOf(double[] original, int newLength)
static boolean[] copyOfRange(boolean[] original, int from, int to)
static byte[] copyOfRange(byte[] original, int from, int to)
static char[] copyOfRange(char[] original, int from, int to)
static short[] copyOfRange(short[] original, int from, int to)
static int[] copyOfRange(int[] original, int from, int to)
static long[] copyOfRange(long[] original, int from, int to)
static float[] copyOfRange(float[] original, int from, int to)
static double[] copyOfRange(double[] original, int from, int to)
泛型,用于copy对象类型,空余使用null填充:
static <T> T[] copyOf(T[] original, int newLength)
static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType)
static <T> T[] copyOfRange(T[] original, int from, int to)
static <T,U> T[] copyOfRange(U[] original, int from, int to, Class<? extends T[]> newType)
注意: Arrays.copyOf底层就是调用System.copyOf。
最后更新于
这有帮助吗?