数组的5中复制方法:
1.for循环复制
public static int[] copy1(int[] arr){
int[] a=new int[arr.length];
for (int i = 0; i <arr.length ; i++) {
a[i]=arr[i];
}
return a;
}
2.public static int[] copyOf(int[] original, int newLength)
参数 :1.复制的数组,2.复制的长度
int []tem=Arrays.copyOf(arr,arr.length);
3.public static int[] copyOfRange(int[] original,int from, int to)
参数:1.from 的初始指数必须在零和original.length之间,包括在内, original[from]的值
被放置在副本的初始元素中(除非from == original.length或from == to )
2. to 的值可以大于original.length在这种情况下0被放置在其索引大于或等于
original.length - from的副本的所有元素中。
int[] arr={1,2,3,4,5};
int[] tmp=Arrays.copyOfRange(arr,0,arr.length+5);
System.out.println(Arrays.toString(tmp));//[1, 2, 3, 4, 5, 0, 0, 0, 0, 0]
4.public static void arraycopy(Object src,int srcPos,Object dest,int destPos, int length)
参数:src - 源数组。
srcPos - 源数组中的起始位置。
dest - 目标数组。
destPos - 目的地数据中的起始位置。
length - 要复制的数组元素的数量。//该值不能大于src.length
System.arraycopy(arr,0,tmp2,0,arr.length);
5.protected Object clone()
int[] arr={1,2,3,4,5};
int[] tmp2=arr.clone();
System.out.println(Arrays.toString(tmp2));
Arrays工具类中的其他方法
1.public static void fill(int[] a, int val)
将指定的int值分配给指定的int数组的每个元素
int[] arr={1,2,3,4,5};
Arrays.fill(arr,2);
System.out.println(Arrays.toString(arr));
2.static void fill(int[] a, int fromIndex, int toIndex, int val)
将指定的int值分配给指定的int数组的指定范围的每个元素。
参数:fromIndex,toIndex是指定数组的下标
int[] arr={1,11,3,4,5};
Arrays.fill(arr,2,arr.length,2);
System.out.println(Arrays.toString(arr));
3.static void sort(int[] a)
按照数字顺序排列指定的数组。(从小到大排序)
int[] arr={1,11,4,3,5};
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
上述方法short,long,char ,byte,double,float数组都有与之类似的方法