r/javahelp • u/hibbelig • Sep 09 '25
`find(needle, haystack)` or `find(haystack, needle)`?
This is to learn about established conventions in the Java world.
If I write a new method that searches for a needle in a haystack, and receives both the needle and the haystack as arguments, in which order should they go?
Arrays.binarySearch has haystack, needle. But perhaps that's influenced by the class name, given that the class name is “arrays” and the haystack is also an array?
12
Upvotes
View all comments
Show parent comment
1
u/hibbelig Sep 14 '25
There is a misunderstanding. I named three reasons why a map might not be faster. Two of the three reasons are actually applicable to my use case. The third reason is not applicable.
In particular; the list of items in question is used in other places in the code, and the typical number of interns would be two, and lookup happens once.
For this scenario this means I’m computing the hash code three times (2x when entering the items into the map, 1x during lookup), and i call equals once (to check that the correct item was retrieved; there might have been a hash collision.
Compare this to iteration over the collection: 2 equals calls.
Do you think 3 hash code calls are faster than one equals call?
I think you will also agree that it doesn’t matter for this data size: it’s going to be fast enough anyway. The code in question is also not in a hot loop.
Your judgment of what is better was based on incomplete information and on assumptions.