It takes an Array removes all of its elements that equals with element parameter - Java Collection Framework

Java examples for Collection Framework:Array Auto Increment

Description

It takes an Array removes all of its elements that equals with element parameter

Demo Code


//package com.java2s;
import java.lang.reflect.Array;

public class Main {
    /**// w  w w . ja v  a 2  s.  c  o m
     *
     * /**
     * It takes an Array removes all of its elements that equals with element
     * parameter
     *
     * @param <T> Type
     * @param typeClass the class of the type of the array
     * @param array the array you want to operate on
     * @param element the element you want to remove
     * @return if there was no change it returns the original array otherwise
     * the reduced array
     */
    public static <T> T[] removeElement(Class<T> typeClass, T[] array,
            T element) {
        int objectCount = contains(typeClass, array, element);
        if (objectCount > 0) {
            @SuppressWarnings("unchecked")
            T[] newArray = (T[]) Array.newInstance(typeClass, array.length
                    - objectCount);
            int j = 0;
            for (T t : array) {
                if (!t.equals(element)) {
                    newArray[j] = t;
                    j++;
                }
            }

            return newArray;
        }
        return array;
    }

    /**
     * Takes an array and counts how many of its elements equals with the
     * parameter
     *
     * @param <T> Type
     * @param typeClass the class of the type of the array
     * @param array the array you want to operate on
     * @param element the element you want to check
     * @return how many times the element exists in the array
     */
    public static <T> int contains(Class<T> typeClass, T[] array, T element) {
        int counter = 0;
        for (T t : array) {
            if (t.equals(element)) {
                counter++;
            }
        }
        return counter;
    }
}

Related Tutorials