Remove element element with index on array - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

Remove element element with index on array

Demo Code


//package com.java2s;
import java.util.ArrayList;
import java.util.List;

public class Main {
    public static void main(String[] argv) throws Exception {
        String[] array = new String[] { "1", "abc", "level", null,
                "java2s.com", "asdf 123" };
        int index = 2;
        System.out.println(java.util.Arrays
                .toString(removeElementInStringArray(array, index)));
    }// w w w. ja v  a  2 s .  c  o m

    /**
     * Remove element element with index on array
     * @param array
     * @param index
     * @return
     */
    public static String[] removeElementInStringArray(String[] array,
            int index) {
        List<String> result = new ArrayList<String>();
        for (int i = 0; i < array.length; i++) {
            if (i != index) {
                result.add(array[i]);
            }
        }
        if (result.size() < 1)
            return null;
        return result.toArray(new String[result.size()]);
    }
}

Related Tutorials