Discuss / Java / 从一个已有的数组{'A', 'B', 'C', 'D', 'E'}中删除索引为2的元素,代码实现

从一个已有的数组{'A', 'B', 'C', 'D', 'E'}中删除索引为2的元素,代码实现

Topic source
import java.lang.reflect.Array;import java.util.*;public class AresTest {    public static void main(String[] args) throws Exception {        Character[] strings={'A', 'B', 'C', 'D', 'E'};        System.out.println(Arrays.toString(strings));        strings=remove(2,strings,Character.class);        System.out.println(Arrays.toString(strings));    }    //使用泛型数组处理    public static <T> T[] remove(int index,T[] chars,Class<T> tClass) throws Exception {        if (index<0||index>chars.length){            throw new Exception("i 参数传递有误");        }        T[] reChars= (T[]) Array.newInstance(tClass, chars.length-1);;        for (int i=0;i<chars.length-1;i++){            if (i>=index){                reChars[i]=chars[i+1];            }else {                reChars[i]=chars[i];            }        }        return reChars;    }}

代码


import java.lang.reflect.Array;
import java.util.*;
public class AresTest {
    public static void main(String[] args) throws Exception {
        Character[] strings={'A', 'B', 'C', 'D', 'E'};        
        System.out.println(Arrays.toString(strings));       
        strings=remove(2,strings,Character.class);      
        System.out.println(Arrays.toString(strings));    
    }
    //使用泛型数组处理   
    public static <T> T[] remove(int index,T[] chars,Class<T> tClass) throws Exception {
        if (index<0||index>chars.length){
            throw new Exception("i 参数传递有误");        
        }
        T[] reChars= (T[]) Array.newInstance(tClass, chars.length-1);
       for (int i=0;i<chars.length-1;i++){
            if (i>=index){
                reChars[i]=chars[i+1];         
              }else {
                reChars[i]=chars[i];         
             }
        }
        return reChars;   
    }
}

  • 1

Reply