How do I determine whether an array contains a particular value in Java?

后端 未结 29 2734
予麋鹿
予麋鹿 2020-11-21 05:00

I have a String[] with values like so:

public static final String[] VALUES = new String[] {\"AB\",\"BC\",\"CD\",\"AE\"};

Given

29条回答
  •  北恋
    北恋 (楼主)
    2020-11-21 05:30

    Just simply implement it by hand:

    public static  boolean contains(final T[] array, final T v) {
        for (final T e : array)
            if (e == v || v != null && v.equals(e))
                return true;
    
        return false;
    }
    

    Improvement:

    The v != null condition is constant inside the method. It always evaluates to the same Boolean value during the method call. So if the input array is big, it is more efficient to evaluate this condition only once, and we can use a simplified/faster condition inside the for loop based on the result. The improved contains() method:

    public static  boolean contains2(final T[] array, final T v) {
        if (v == null) {
            for (final T e : array)
                if (e == null)
                    return true;
        } 
        else {
            for (final T e : array)
                if (e == v || v.equals(e))
                    return true;
        }
    
        return false;
    }
    

提交回复
热议问题