Someone has to have asked this before, but I can't find it :-(. Does Java have a built-function to allow me to linearly search for an element in an array or do I have to just use a for loop?
Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.
You might want to consider using a Collection implementation instead of a flat array.
The Collection interface defines a contains(Object o) method, which returns true/false.
ArrayList implementation defines an indexOf(Object 0), which gives an index, but that method is not on all collection implementations.
Both these methods require proper implementations of the equals method, and you probable want a properly implemented hashCode method just in case you are using a hash based Collection (e.g. HashSet).
You can use one of the many Arrays.binarySearch()
methods. Keep in mind that the array must be sorted first.
There is a contains
method for lists, so you should be able to do:
Arrays.asList(yourArray).contains(yourObject);
Warning: this might not do what you (or I) expect, see Tom's comment below.