一、基本定义
Arrays类,全路径java.util.Arrays,主要功能为操作数组,Arrays类的所有方法均为静态方法,所以
调用方式全部为Arrays.方法名
二、常用方法
1. <T> List<T> asList(T... a)
可以将数组转化为相应的list集合,但是也只能转化为list,asList方法内部构建了一个内部静态类ArrayList
,
这个ArrayList
也继承自AbstractList
,但并不是我们集合中常用的ArrayList
,这两者是有区别的,需注意,
内部静态类AbstractList
也实现了contains,forEach,replaceAll,sort,toArray
等方法,但add,remove
等方法则没有
Integer[] array = new Integer[]{
1,2,3};
int[] array2 = new int[]{
1,2,3};
List<Integer> list1 = Arrays.asList(1,2,3);
List<Integer> list2 = Arrays.asList(array);
List<int[]> list3 = Arrays.asList(array2);
void fill(int[] a, int val)、void fill(int[] a, int fromIndex, int toIndex, int val)、void fill(Object[] a, Object val)、void fill(Object[] a, int fromIndex, int toIndex, Object val)
fill方法有多个重载,分别对应几种基本数据类型以及引用类型(Object),
fill(int[] a, int val)
会将整个数组的值全部覆盖为val
fill(int[] a, int fromIndex, int toIndex, int val)
则提供了可选的开头和结尾(不包括)
int[] array = new int[]{
1,2,3};
Arrays.fill(array, 1);
Arrays.fill(array, 0, 2, 1);// {1,1,3}
String[] str = {
"123"};
Arrays.fill(str, "1");
源码如下:
我们可以看到可选开头结尾的重载方法会先做数组越界的校验,防止非法输入
/** * Assigns the specified double value to each element of the specified
* range of the specified array of doubles. The range to be filled
* extends from index <tt>fromIndex</tt>, inclusive, to index
* <tt>toIndex</tt>, exclusive. (If <tt>fromIndex==toIndex</tt>, the
* range to be filled is empty.)
*
* @param a the array to be filled
* @param fromIndex the index of the first element (inclusive) to be
* filled with the specified value
* @param toIndex the index of the last element (exclusive) to be
* filled with the specified value
* @param val the value to be stored in all elements of the array
* @throws IllegalArgumentException if <tt>fromIndex > toIndex</tt>
* @throws ArrayIndexOutOfBoundsException if <tt>fromIndex < 0</tt> or
* <tt>toIndex > a.length</tt> */
public static void fill(double