Where is Java's Array indexOf?
Java arrays don't come with a built-in indexOf
method. You'll have to create your own. Here it is in a nutshell:
Just use it like so:
A one-liner ready to be unleash its power on your code.
Primitive Arrays vs. Object Arrays
When you're dealing with primitives...
Remember, Arrays.asList()
won't work directly on primitive arrays. It sees this array as a single entity, an object, a monolith.
Fear not! Convert your "monolith" into boxed equivalents first:
Sorted arrays? More like sorted chocolates
Happy day! You have a sorted array like chocolates neatly placed in their box. Use Arrays.binarySearch()
. It's lightning quick - O(log n):
The secret lies in negative returns - they're a sign from above (or below) indicating the element isn't present.
Arrays... meet Collections
Arrays are social now
With Arrays.asList()
, your arrays can now mingle with other collections. They can use sophisticated methods like indexOf
and lastIndexOf
from the List interface:
Becareful though, once an array becomes a list, it can't be resized. It's a fixed-size list. It's like moving out but your room never gets any bigger.
Welcome to the extension family
Surprise, indexOf
for arrays already exist in Apache Commons Lang and Guava libraries:
- Apache Commons Lang's
ArrayUtils.indexOf()
:
- Guava's
Ints.indexOf()
for primitives:
Suddenly, arrays don't seem that primitive now, do they?
Playing Frankenstein: Custom indexOf
Your own creation
Craft your indexOf
, the world is your oyster or in this case, your array. Add null checks, custom behavior, your CV:
Custom sorting party: Bring your own Comparator
Arrays.binarySearch()
doesn't just accept arrays and keys. Bring your own Comparator
for that custom sorting:
Performance Jugglery
Choose your fighter, wisely
The method you pick could make or break your performance. Let that sink in:
- For tiny arrays, a simple
for
loop should do the job. Like mowing a small lawn. binarySearch
: Your go-to method for large, sorted arrays. Just don't use it on unsorted arrays, they'll give undefined results. Binary search on unsorted arrays is like looking for your socks in the washing machine while it's running.- Boxing primitives has a tiny overhead. If you're dealing with primitives, libraries like Guava are efficient.
Stream API: Because why not?
The power of Java 8 Stream API: One line, functional-style operations. It's like driving an automatic, but with benefits on large data sets:
Was this article helpful?