数组工具类的使用
package demo02;
/*
* 数组工具类的使用
* 数组的复制操作
* */
import java.util.*;
public class Test10 {
public static void main(String[] args) {
int[] arr = {3,4,2,66,75,4,322,55,33,85,39};
System.out.println(Arrays.toString(arr));
//排序问题
Arrays.sort(arr);
System.out.println(Arrays.toString(arr));
/*
* 在数组中快速的查询给定元素出现的位置
* 若果找到元素,返回元素的索引,没找到返回一个负数
* Array.binarySearch在使用时,要求数组必须是升序的
* */
int index = Arrays.binarySearch(arr,33);
System.out.println(index);
/*
* 快速的遍历数组
* 返回给定数组的字符串表达形式
* */
String arrs = Arrays.toString(arr);
System.out.println(arrs);
//数组复制功能
int[] arr1 = {1,2,3,4,5,6};
//将arr1存储的引用地址复制给arr2
//int[] arr2 = arr1;
int[] arr2 = Arrays.copyOf(arr1,arr1.length);
arr1[0] = 100;
System.out.println(Arrays.toString(arr1));
System.out.println(Arrays.toString(arr2));
/*
* 数组的复制操作
* src:原数组,要复制的数组
* srcPos:起始索引,从原数组中的哪个索引开始复制
* dest:目标数组,数组复制到哪个数组
* destPost:目标索引,目标数组从哪里开始复制
* length:数组长度,复制多少个元素
* */
int[] arr3 = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
int[] arr4 = new int[10];
System.arraycopy(arr3,9,arr4,1,5);
System.out.println(Arrays.toString(arr3));
System.out.println(Arrays.toString(arr4));
/*
* Arrays.copyOf的内部功能就是使用System.arraycopy的方法实现的
* Array.copyOf起始就是对System.arraycopy一个简单的封装
* */
}
}
执行代码如下: