*/
public class ArraysTest2 {
public void insert(){
int[] a = {1,2,3,4,5,6};
// 如果要插入一个数,那么这个数组需要扩容才可以
a = Arrays.copyOf(a, a.length+1);
System.out.println("扩容后的数组:"+Arrays.toString(a));
// 要在第二个位置插入数则遍历这个数组,还要移位,因为扩容了,所以最后一个数字会为0,那么就从后面往前遍历,把之前的移位到后面来,到你要插入的位置即可。
for(int i=a.length-1;i>2;i--){
a[i] = a[i-1];
}
a[2] = 100;
System.out.println("扩容移位后的数组:"+Arrays.toString(a));
}
}
arraycopy方法我们看源码的时候
发现是native声明,并没有看到实现
在java中native声明称为本地方法
它是在java中声明方法,用c or c++来
实现方法,然后java调用
这门技术在java中称为JNI
arraycopy效率很高
*/
public class ArraysCopyTest1 {
public void getArraysCopyTest1(){
int[] a = {1,2,3,4,5};
int[] b = new int[a.length];
int[] c = new int[20];
for(int i=0;i<b.length;i++){
b[i] = a[i];//copy
}
System.out.println("复制a数组后b="+Arrays.toString(b));
System.arraycopy(a, 0, c, 10, a.length);
System.out.println("arraycopy赋值a数组到c数组中:"+Arrays.toString(c));
int[] a1={1,2,3,4,5};
a1 = Arrays.copyOf(a, 2*a1.length);
System.out.println("Arrays.copyof:"+Arrays.toString(a1));
/**
* 大概看下arraycopy和copyof的区别:1.arraycopy是直接调用jni写好的方法对数组的复制,需要有原数组是属于一种不完全的合并,也就是说上述的的c数组20个长度,如果把a复制进来那么就会有15个位置是0;
* 2.copyof是在内部新建一个数组然后把内容复制进去。那么如果你长度不够当然会出现越界错误了。
*/
}