集册 Java实例教程 它接受一个数组移除其所有与元素参数相等的元素

它接受一个数组移除其所有与元素参数相等的元素

欢马劈雪     最近更新时间:2020-01-02 10:19:05

524
它需要Array删除所有与element参数相等的元素


//package com.nowjava;
/**
来 自 n o w j a v a . c o m
**/

import java.lang.reflect.Array;


public class Main {

    /**

     *

     * /**

     * 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++;

                }
                /** from 
                nowjava**/

            }


            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 <
展开阅读全文