// 用泛型实现通用数组的删除操作
package test;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
public class Test1 {
public static <T> T[] deleteArray(T[] items,int index) {
if (items == null || items.length == 0 || index < 0
|| index > items.length - 1) {
return items;
}
T[] newItems = (T[]) Array.newInstance(items.getClass().getComponentType(), items.length - 1);
if(index == 0){
// first
System.arraycopy(items, 1, newItems, 0, newItems.length);
}else if(index == items.length - 1){
// end
System.arraycopy(items, 0, newItems, 0, newItems.length);
}else{
// middle
System.arraycopy(items, 0, newItems, 0, index);
System.arraycopy(items, index+1, newItems, index, items.length - index -1);
}
return newItems;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
// first
String[] first = new String[]{"0","1","2"};
String[] rt = deleteArray(first,0);
printArray(rt);
// end
Integer[] end = new Integer[]{0,1,2};
Integer[] rt1 = deleteArray(end,2);
printIntegerArray(rt1);
}
public static void printArray(String[] array){
System.out.println("start ====================");
for(String s:array){
System.out.println(s);
}
System.out.println("end ====================");
List<String> a = new ArrayList<String>();
}
public static void printIntegerArray(Integer[] array){
System.out.println("start ====================");
for(Integer s:array){
System.out.println(s);
}
System.out.println("end ====================");
List<String> a = new ArrayList<String>();
}
}