package another; import java.util.Arrays; import java.util.List; /** * 数组知识回顾 * @author ChristineBassoon */ public class Array { public static void main(String[] args) { //1. 新建数组的三种方式 int[] arr1 = new int[3]; int[] arr2 = {3,2,4,1}; int[] arr3 = new int[]{5,7,9,0,3,5}; //填充数组 Arrays.fill(arr1, 10);//[10,10,10] //2. 数组元素默认值 int[] arr_int = new int[3];//[0,0,0] String[] arr_str = new String[3];//[null,null,null] //3. 输出数组内容,如:[0,0,0,0] Arrays.toString(arr1); /*4. 数组自动排序(从小到大) * 一、 数组全排序 Arrays.sort(T[]) * 二、 特定位置排序 Arrays.sort(T[], fromIndex, toIndex); */ Arrays.sort(arr2);//[1,2,3,4] Arrays.sort(arr3,1,3);//只排序下标1-3的元素 [5,0,7,9,3,5] //5. 数组扩容、复制等————基于方法System.arraycopy(src, srcPos, dest, destPos, length); /* * (1) 扩容 * Arrays.copyOf(original, newLength) * 扩充的元素加至原序列末尾 */ int[] arr4 = Arrays.copyOf(arr2, arr2.length+2);//[1,2,3,4,0,0] /* * (2) 缩容 * Arrays.copyOf(original, newLength) * 根据指定长度,只保留原数组的头部 * */ int[] arr5 = Arrays.copyOf(arr2, 2);// [1,2] /* * (3) 截取(同数组中) * Arrays.copyOfRange(original, from, to) * 范围为[from,to),超出则抛IllegalArgumentException异常 */ int[] arr6 = Arrays.copyOfRange(arr2, 1, 3);//[2,3] /* * 用外部数组元素替换本数组指定位置 * System.arraycopy(src, srcPos, dest, destPos, length); length表示需要复制的元素个数 */ String[] t1 = {"a","b","c","d"}; String[] t2 = {"Apple","Boy","C","D"}; System.arraycopy(t1, 1, t2, 2, 1); System.out.println(Arrays.toString(t2));//[Apple, Boy, b, D] //数组转换为List类型 List list = Arrays.asList(arr2); } }