Depending on how large your array of int will be, you will get much better performance if you use collections and .contains
rather than iterating over the array one element at a time:
import static org.junit.Assert.assertTrue;
import java.util.HashSet;
import org.junit.Before;
import org.junit.Test;
public class IntLookupTest {
int numberOfInts = 500000;
int toFind = 200000;
int[] array;
HashSet<Integer> intSet;
@Before
public void initializeArrayAndSet() {
array = new int[numberOfInts];
intSet = new HashSet<Integer>();
for(int i = 0; i < numberOfInts; i++) {
array[i] = i;
intSet.add(i);
}
}
@Test
public void lookupUsingCollections() {
assertTrue(intSet.contains(toFind));
}
@Test
public void iterateArray() {
assertTrue(contains(array, toFind));
}
public boolean contains(final int[] array, final int key) {
for (final int i : array) {
if (i == key) {
return true;
}
}
return false;
}
}