Java Array Remove removeAll(T[] items, T item)

Here you can find the source of removeAll(T[] items, T item)

Description

Remove any occurrence of a given value from an array.

License

Open Source License

Parameter

Parameter Description
items a parameter

Declaration

public static <T> T[] removeAll(T[] items, T item) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.util.Arrays;

public class Main {
    /**//from   w w  w.j  av  a2  s .co m
     * Remove any occurrence of a given value from an array. The resulting array
     * may be shorter in length, but the relative position of all other items
     * will remain unchanged. This algorithm is robust to <code>null</code>. The
     * <code>items</code> array may contain <code>null</code> values and the
     * <code>item</code> may itself be <code>null</code> (in which case, all
     * <code>null</code> values are removed).
     *
     * @param items
     * @return
     */
    public static <T> T[] removeAll(T[] items, T item) {
        int count = 0;
        // First, determine the number of elements which will be removed
        for (int i = 0; i != items.length; ++i) {
            T ith = items[i];
            if (ith == item || (item != null && item.equals(ith))) {
                count++;
            }
        }
        // Second, eliminate duplicates (if any)
        if (count == 0) {
            // nothing actually needs to be removed
            return items;
        } else {
            T[] nItems = Arrays.copyOf(items, items.length - count);
            for (int i = 0, j = 0; i != items.length; ++i) {
                T ith = items[i];
                if (ith == item || (item != null && item.equals(ith))) {
                    // skip item
                } else {
                    nItems[j++] = ith;
                }
            }
            return nItems;
        }
    }
}

Related

  1. remove(String[] initial, String... toExclude)
  2. remove(String[] target, String[] needRemoved)
  3. remove(T[] a, int i)
  4. removeAll(E[] array, Object... toRemove)
  5. removeAll(T[] array, Collection toRemove)
  6. RemoveArgs(String[] args, int startIndex)
  7. removeAt(T[] array, int index)
  8. removeByPrefix(String[] array, String prefix)
  9. removeByteOrderMark(final byte[] input)