package 数组2;
import java.util.Arrays;
/**
- 测试数组的拷贝
- @author
*/
public class TestArrayCopy {
public static void main(String[] args) {
/*int[] a = {1,2,3,4};
int[] b = new int[10];
System.arraycopy(a, 1, b, 1, 2);
for(int i = 0; i<b.length; i++){
System.out.println(i+"->"+b[i]);}*/
// String[] str = {“aa”,“bb”,“cc”,“dd”};
// removeElment(str,1);
// System.out.println(Arrays.toString(str));
//
// str = extendRange(str);
int[] a = {1,2,3,5,6};
a = testBasicCopy2(a, 4, 3);
System.out.println(Arrays.toString(a));
}
public static void testBasicCopy(){
int[] a = {1,2,3,4};
int[] b = new int[10];
System.arraycopy(a, 1, b, 1, 2);
for(int i = 0; i<b.length; i++){
System.out.println(i+"->"+b[i]);}
}
//测试数组中删除某个元素(本质上还是数组的拷贝)
public static void testBasicCopy1(){
String[] s1 = {"aa","bb","cc","dd","ee"};
//String[] s2 = new String[5];
System.arraycopy(s1, 3, s1, 3-1, s1.length-3);
Arrays.toString(s1);
}
//删除数组中指定索引位置的元素,并将原数组返回
public static String[] removeElment(String[] s,int index){
//String[] s = {"aa","bb","cc","dd","ee"};
//String[] s2 = new String[5];
index +=1;
System.arraycopy(s, index, s, index-1, s.length-index);
s[s.length-1] = null;
return s;
}
//数组的扩容(本质上是:定义一个更大的数组,然后将原数组内容原封不动拷贝到新数组)
public static String[] extendRange(String[] s1){
//String[] s1 = {"aa","bb","cc"};
String[] s2 = new String[s1.length+10];
System.arraycopy(s1, 0, s2, 0, s1.length);
for(String i:s2){
System.out.println(i);
}
return s2;
}
//指定位置增加元素
public static int[] testBasicCopy2(int[] m,int a,int b){//a 为所插入元素 b为所插入位置
int[] s1 = new int[m.length+10];
int[] s2 = new int[m.length+10];
System.arraycopy(m, 0, s1, 0, b);
System.arraycopy(m, b, s2, 0, m.length-b);
s1[b] = a;
System.arraycopy(s2, 0, s1, 4, m.length);
return s1;
}
}