No “contains” method for arrays in Java

Sergii Riabokon
1 min readNov 28, 2022

--

Modern Java 8 (as well as 11, 17) still misses contains method for arrays. In case you need to check an array for holding an element, you have to either:

  • convert it to a list
Arrays.asList(sampleArray).contains(sampleObject);
  • use Stream API
boolean found = Arrays.stream(haystack).anyMatch(x -> needle.equals(x));
  • write the whole thing yourself with for each
boolean found = false;

for(Fruit f:fruits) {
found |= f.equals(targetFruit);
if (found) break;
}

That is a bit of a pity. From good old C you could use a pointer with malloc function to dynamically allocate memory for an array or allocate memory during array initialisation. Both cases the performance is better than using dynamic data structures of lists. However during daily tasks on modern computers the difference between arrays and lists in Java is rarely noticed as it is a memory managed language that runs on top of a virtual machine. Nevertheless it still clicks with that old C-thing for not using the memory in an efficient way.

--

--

Sergii Riabokon
Sergii Riabokon

Written by Sergii Riabokon

Technical blog about programming and related stuff. Mostly contains my personal discoveries and some memorable notes.

No responses yet