In Java, Remove Integer From Array At Given Index

public class Test{

    public static void main(String[]arg){
        removeAt(null, 0, 3);
        removeAt(new int[0], 0, 3);
        removeAt(new int[1], 0, 3);
        removeAt(new int[1], 2, 0);

        int[]nums = {2,3,5,1,6,4,0,0};
        int count = nums.length-2;
        dump(nums, count);
        count = removeAt(nums, count, 3);
        dump(nums, count);
    }

    private static int removeAt(final int[]arr, int count, final int at){
        if(null == arr || 0 == arr.length){
            System.out.println("Error: Invalid array!");
            return count;
        }
        if(0 > at || arr.length <= at){
            System.out.println("Error: Invalid index!");
            return count;
        }
        if(0 > count || arr.length < count){
            System.out.println("Error: Invalid count!");
            return count;
        }
        int j = count-1;
        for(int i = at; j > i; i ++)
            arr[i] = arr[i+1];
        arr[j] = 0;
        return j;
    }

    private static void dump(final int[]arr, final int count){
        System.out.printf("Count: %d\n", count);
        System.out.println("Array Dump");
        for(int n: arr)
            System.out.printf("%d ", n);
        System.out.println();
    }
}
Download

Comments

Popular posts from this blog