Generic method to check if an array contains an element - Java Collection Framework

Java examples for Collection Framework:Array Element

Description

Generic method to check if an array contains an element

Demo Code


//package com.book2s;

public class Main {

    public static <T> boolean contains(T[] array, T value) {
        final Class<?> componetType = array.getClass().getComponentType();
        boolean isPrimitive = false;
        if (null != componetType) {
            isPrimitive = componetType.isPrimitive();
        }/*w w w  .j  a va  2s . c  om*/
        for (T t : array) {
            if (t == value) {
                return true;
            } else if (false == isPrimitive && null != value
                    && value.equals(t)) {
                return true;
            }
        }
        return false;
    }
}

Related Tutorials