Generic method to check if an element is contained in an array - Java Collection Framework

Java examples for Collection Framework:Array Contain

Description

Generic method to check if an element is contained in an array

Demo Code


//package com.java2s;

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  v a2  s  .co m*/
        for (T t : array) {
            if (t == value) {
                return true;
            } else if (false == isPrimitive && null != value
                    && value.equals(t)) {
                return true;
            }
        }
        return false;
    }
}

Related Tutorials