I have a String[]
with values like so:
public static final String[] VALUES = new String[] {\"AB\",\"BC\",\"CD\",\"AE\"};
Given
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;
}