top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to test if an Array contains a value in Java using Linear Search ?

+2 votes
467 views
How to test if an Array contains a value in Java using Linear Search ?
posted Nov 2, 2015 by Shyam

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

0 votes

This method loop through array and use equals() method to search element. This actually performs a linear search over array in Java and return true if array has provided value.

public static <T> 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; 
}
answer Nov 2, 2015 by Salil Agrawal
...