Java Check if the element is in the array.

Possible duplicate:
In Java, how can I check if an Array contains a specific value?

I have an array setup as follows:

Material[] blockedlevel1 = { Material.mymaterialone, Material.mymaterialtwo }; 

How to find out if the material is in this array?

+4
source share
3 answers

How to find it in an array?

 for (Material m : blockedlevel1) { if (m.equals(searchedMaterial)) { // assuming that equals() was overriden // found it! do something with it break; } } 
+7
source

If you need an easy way to check if an element is part of a collection, you should probably consider another data structure such as Set (and use contains ()). With an array, you can only iterate over elements and compare them.

+3
source

How about searching with the Arrays class?

See Arrays # binary search

Or as someone suggested, turn your array into List and use contains () . Remember that you may need to override the Material # equals method.

+1
source

Source: https://habr.com/ru/post/1401506/


All Articles