remove Item From Array - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

remove Item From Array

Demo Code


//package com.java2s;

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

    public static String[] removeFromList(String object, String[] array) {
        String[] ret = null;
        int remIndex = -1;
        try {
            for (int i = 0; i < array.length; i++) {
                if (object.equals(array[i])) {
                    remIndex = i;
                    break;
                }
            }
            if (remIndex != -1) {
                ret = new String[array.length - 1];
                int ri = 0;
                int wi = 0;
                while (wi < ret.length) {
                    if (ri == remIndex) {
                        ri++;
                    } else {
                        ret[wi] = array[ri];
                        ri++;
                        wi++;
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Objects aren't same type");
        }
        return ret;
    }
}

Related Tutorials