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?
5 Answers
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.
 
    
    - 36,802
- 9
- 76
- 89
- 
                    2Thats pretty short, but this use case is common enough that they really should have added a function into the language – Casebash Aug 02 '10 at 00:15
- 
                    4Be careful not to use that with primitive arrays. – Tom Hawtin - tackline Aug 02 '10 at 01:30
- 
                    12@Casebash It compiles but doesn't do what you expect. Because of evil varargs, the argument gets treated as an array of arrays of primitives. – Tom Hawtin - tackline Aug 02 '10 at 02:08
- 
                    Look at https://stackoverflow.com/questions/9981823/why-is-indexof-failing-to-find-the-object – user2743055 Jul 13 '21 at 08:57
With Java 8, you can do this:
int[] haystack = {1, 2, 3};
int needle = 3;
boolean found = Arrays.stream(haystack).anyMatch(x -> x == needle);
You'd need to do
boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));
if you're working with objects.
 
    
    - 11,678
- 10
- 56
- 60
- 
                    True, but if you're working with an `ArrayList`, doing `boolean found = haystack.contains(needle)` is much easier to read. – Trenton Nov 20 '19 at 19:30
Use a for loop. There's nothing built into array. Or switch to a java.util Collection class.
 
    
    - 305,152
- 44
- 369
- 561
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 o), 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 probably want a properly implemented hashCode() method just in case you are using a hash based Collection (e.g. HashSet).
 
    
    - 15,970
- 10
- 45
- 59
 
    
    - 118,147
- 33
- 203
- 236
You can use one of the many Arrays.binarySearch() methods.  Keep in mind that the array must be sorted first.
 
    
    - 28,904
- 13
- 79
- 85
- 
                    1That's an option only is elements of array are comparable themselves. – Nikita Rybak Aug 02 '10 at 00:02
- 
                    2We can only assume that this is the case, e.g. an array of ints, Strings, etc. You could always provide a custom [`Comparator`](http://download.oracle.com/javase/6/docs/api/java/util/Comparator.html) to sort and search if needed. – krock Aug 02 '10 at 00:13
- 
                    2
 
    